Excel VBA检查是否打开工作簿,如果没有则打开它

时间:2017-10-12 11:31:31

标签: vba excel-vba excel

我在下面输入的代码无法正常工作。尝试运行宏时,我收到错误400。您能否对此代码进行一些审核?我不确定问题是否与我所指的函数变量有关。

Sub AutoFinal()    
    Dim final_wb As Workbook, shop_stat_wb As Workbook 
    Dim book2 As String
    book2 = "Workbook_I_need.xlsx"
    Dim book2path As String
    book2path = ThisWorkbook.Path & "\" & book2
    Set final_wb = ThisWorkbook
    If IsOpen(book2) = False Then Workbooks.Open (book2path)
    Set shop_stat_wb = Workbooks(book2)    
End Sub

Function IsOpen(strWkbNm As String) As Boolean    
    On Error Resume Next

    Dim wBook As Workbook
    Set wBook = Workbooks(strWkbNm)

    If wBook Is Nothing Then    'Not open
        IsOpen = False
        Set wBook = Nothing
        On Error GoTo 0
    Else
        IsOpen = True
        Set wBook = Nothing
        On Error GoTo 0
    End If    
End Function

1 个答案:

答案 0 :(得分:6)

IsOpen可以简化:

Function IsOpen(strWkbNm As String) As Boolean
    Dim wb As Workbook
    On Error Resume Next
    Set wb = Workbooks(strWkbNm)
    IsOpen = Err.Number = 0
    On Error GoTo 0
End Function

以下是我的写作方式:

Sub AutoFinal2()
    Dim final_wb As Workbook, shop_stat_wb As Workbook
    Dim WorkbookFullName As String

    WorkbookFullName = ThisWorkbook.Path & "\" & book2
    Set final_wb = ThisWorkbook
    Set shop_stat_wb = getWorkbook(WorkbookFullName)

    If shop_stat_wb Is Nothing Then
        MsgBox "File not found:" & vbCrLf & WorkbookFullName, vbCritical, "AutoFinal2 Cancelled"
        Exit Sub
    End If
End Sub

Function getWorkbook(WorkbookFullName As String) As Workbook
    Dim wb As Workbook
    For Each wb In Workbooks
        If wb.FullName = WorkbookFullName Then Exit For
    Next

    If wb Is Nothing Then
        If Len(Dir(WorkbookFullName)) > 0 Then
            Set wb = Workbooks.Open(WorkbookFullName)
        End If
    End If
    Set getWorkbook = wb
End Function