文章背景:在操作某个Excel文件时,有时需要判断该文件是否已打开。下面提供两种自定义函数。
(1)遍历法
代码语言:javascript复制Function IsWbOpen1(strPath As String) As Boolean
'如果目标工作簿已打开则返回TRUE,否则返回FALSE
'Codes adapted from:https://zhuanlan.zhihu.com/p/30977643
'strPath:指定文件的全路径(Full path)
Dim i As Integer
For i = Workbooks.Count To 1 Step -1
If Workbooks(i).FullName = strPath Then Exit For
Next
If i = 0 Then
IsWbOpen1 = False
Else
IsWbOpen1 = True
End If
End Function
示例:判断文件指定路径的文件是否已打开,如果未打开,则打开该文件。
代码语言:javascript复制Sub Test1()
Dim str_name As String, str_path As String
str_name = "test1.xlsx"
str_path = "E:test1.xlsx"
If IsWbOpen1(str_path) Then
Workbooks(str_name).Activate
Else
Workbooks.Open (str_path)
End If
End Sub
如果已打开的Excel文件较多,则遍历法比较费时间,下面介绍试错法。
(2)试错法
代码语言:javascript复制Function IsWbOpen2(strName As String) As Boolean
'如果目标工作簿已打开则返回TRUE,否则返回FALSE
'Codes adapted from:https://zhuanlan.zhihu.com/p/30977643
'strName:指定文件的文件名(File name)
Dim wk As Workbook
'如果工作簿没打开,程序会报错,故使用On Error Resume Next
On Error Resume Next
Set wk = Workbooks(strName)
If Err.Number = 0 Then
IsWbOpen2 = True
Else
IsWbOpen2 = False
End If
On Error GoTo 0
End Function
示例:判断文件是否已打开(通过文件名来判断),如果未打开,则打开该文件。
代码语言:javascript复制Sub Test2()
Dim str_name As String, str_path As String
str_name = "test1.xlsx"
str_path = "E:test1.xlsx"
If IsWbOpen2(str_name) Then
Workbooks(str_name).Activate
Else
Workbooks.Open (str_path)
End If
End Sub
参考资料:
[1] VBA如何判断工作簿是否打开(https://zhuanlan.zhihu.com/p/30977643)