2017-10-12 101 views
1

下面的代碼工作不正常。嘗試運行宏時遇到錯誤400。你可以稍微回顧一下這段代碼嗎?我不確定問題是否與我引用的函數變量不同。Excel VBA檢查工作簿是否打開,如果不是,打開它

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 
+0

它錯誤在哪一行? – Zerk

+0

我想這個錯誤出現在Workbooks.Open的行上。在那裏設置一個斷點,並檢查Path是否正確,並且指向一個現有的文件。 – z32a7ul

+0

@ z32a7ul是的,您對錯誤行是正確的。我檢查了一條路徑是正確的。設置斷點不是一個問題,但我可以用這個來實現嗎? – RafMil

回答

5

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 
+0

@Thomsa Inzina非常感謝這段代碼!我喜歡他們這樣做,無論如何,你指的是book2沒有宣佈。但是增加2條線解決了一個問題。根據IsOpen函數,變量strWKbNm也應該放在我的Sub()中才能正常工作? – RafMil

相關問題