【ExcelVBA】ブックの開閉確認
基本編
ブックの開閉確認
Sub Sample()
Dim TargetWB As String
Dim TargetChk As Variant
TargetWB = "TEST.xlsx" '対象ブック名明記
On Error Resume Next ' エラー発生時の継続処理有効化
Set TargetChk = Nothing
Set TargetChk = Workbooks(TargetWB)
On Error GoTo 0 ' エラー発生時の継続処理無効化
If TargetChk Is Nothing Then
MsgBox TargetWB & " は開いてる?"
Else
MsgBox TargetWB & " は開いてるよ!"
End If
Set TargetChk = Nothing
End Sub
応用編
ファイル存在確認とブック開閉確認を続けてする
VWorkbooks.Open メソッドでファイルを開く前に、そのファイルが実在することや、ブックが閉じていることを等を事前に確認したいときのサンプルコードです。
Sub 主処理()
Dim FilePath As String
FilePath = "C:\temp\TEST.xlsx" 'ファイルパス名を明記する
Call ファイルの存在確認(FilePath)
Call ブックの開閉確認(FilePath)
End Sub
Sub ファイルの存在確認(ByVal FilePath As String)
Dim FS As Object
Set FS = CreateObject("Scripting.FileSystemObject")
If FS.FileExists(FilePath) Then
MsgBox "ファイルある!"
Else
MsgBox "ファイルない!中止します!", vbCritical
End
End If
Set FS = Nothing
End Sub
Sub ブックの開閉確認(ByVal FilePath As String)
Dim TargetWB As String
Dim TargetChk As Variant
'ファイルパスからファイル名のみ取得
TargetWB = Right(FilePath, InStr(StrReverse(FilePath), "\") - 1)
On Error Resume Next ' エラー発生時の継続処理有効化
Set TargetChk = Nothing
Set TargetChk = Workbooks(TargetWB)
On Error GoTo 0 ' エラー発生時の継続処理無効化
If TargetChk Is Nothing Then
MsgBox "このブック名は開いていない"
'Workbooks.Open FilePath 'ファイルを開く
Else
MsgBox "このブック名は開いている"
End If
Set TargetChk = Nothing
End Sub
※5行目のファイルパス名を書き換えてください。※48行目の Workbooks.Open メソッドのコメントアウトを解除することで、ファイルは開くようになります。




ディスカッション
コメント一覧
まだ、コメントがありません