通过Variable和If语句引用外部工作簿VBA

时间:2015-12-15 22:52:24

标签: excel vba excel-vba

目前我的代码看起来像这样,并且工作正常

    Dim WorkbookVar As Workbook
    Dim Path As String
    Path = "C:\Path.xlsx"
    Set WorkbookVariable = Workbooks.Open (Filename:=MCDistroNumberPath)

但是我希望它更进一步,并且有一个if语句说If此工作簿已经打开Then跳过它并开始运行我的其余宏。

我将如何做到这一点?

1 个答案:

答案 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函数将仅返回没有路径的文件名。如果具有该名称的工作簿已打开,则它将返回该工作簿。如果没有,它会尝试打开它。