目前我的代码看起来像这样,并且工作正常
Dim WorkbookVar As Workbook
Dim Path As String
Path = "C:\Path.xlsx"
Set WorkbookVariable = Workbooks.Open (Filename:=MCDistroNumberPath)
但是我希望它更进一步,并且有一个if语句说If
此工作簿已经打开Then
跳过它并开始运行我的其余宏。
我将如何做到这一点?
答案 0 :(得分:3)
考虑将它放入自己的功能中,如下所示。
Public Function GetOrOpenWorkbook(ByVal sFullPath As String) As Workbook
Dim wbReturn As Workbook
On Error Resume Next
Set wbReturn = Workbooks(Dir(sFullPath))
On Error GoTo 0
If wbReturn Is Nothing Then
Set wbReturn = Workbooks.Open(sFullPath)
End If
Set GetOrOpenWorkbook = wbReturn
End Function
Sub test()
Dim wb As Workbook
Set wb = GetOrOpenWorkbook("C:\Path\Path.xlsx")
End Sub
Dir
函数将仅返回没有路径的文件名。如果具有该名称的工作簿已打开,则它将返回该工作簿。如果没有,它会尝试打开它。