简体   繁体   English

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

[英]Excel VBA checking if workbook is opened and opening it if not

code I put below is not working properly.我放在下面的代码无法正常工作。 I am getting error 400 when try to run macro.尝试运行宏时出现错误 400。 Could you take a little review of this code?你能稍微回顾一下这段代码吗? I am not sure if problem is not with function variable I am refering to.我不确定问题是否与我所指的函数变量有关。

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

IsOpen can be simplified: 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

Here is how I would write it:这是我将如何编写它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM