Excel VBA checking if workbook is opened and opening it if not

后端 未结 1 1310
情深已故
情深已故 2021-01-25 16:29

code I put below is not working properly. I am getting error 400 when try to run macro. Could you take a little review of this code? I am not sure if problem is not with functio

1条回答
  •  孤独总比滥情好
    2021-01-25 16:59

    IsOpen can be simplified:

    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
    

    0 讨论(0)
提交回复
热议问题