2015-02-11 132 views
0

我在VBA程序的工作,我需要做以下幾點:檢查工作簿是否存在,如果是,則檢查它是否打開。如果打開,然後激活,如果關閉再打開它

當單擊該按鈕(宏運行):

  1. 檢查如果MS EXCEL工作簿存在於文件夾中。如果不是,則發出消息「工作簿不存在」,並且VBA程序應該結束。

  2. 如果工作簿存在,請檢查工作簿是關閉還是打開。如果它關閉了,那麼打開工作簿並且VBA程序應該以更進一步的步驟移動。

  3. 如果工作表是打開的,那麼激活工作簿,VBA程序應該移動更多的步驟。

到目前爲止,我已經寫了這一點,但它不工作:

Sub test() 
    Dim WbookCheck As Workbook 

    On Error Resume Next 
    Set WbookCheck = Workbooks("Weekly Report.xls") 
    On Error GoTo 0 
    filepaths = "c:\clients\work\Weekly Report.xls" 
    If Dir("filepaths") = False Then 
     MsgBox "Please save the latest file under the name 'US Sector Flow Weekly Report' and run the macro again" 
     Exit Sub 
    ElseIf WbookCheck Is Nothing Then 
     Workbooks.Open "c:\clients\work\Weekly Report.xls" 
    Else 
     WbookCheck.Activate 
    End If 
Workbooks("Weekly Report.xls").Activate 

Sheets("This week").Select 
    Sheets("This week").Copy Before:=Workbooks(_ 
     "Consolidated.xls").Sheets(1) 

End Sub 
+3

「不工作」可能是有點更明確的 - 當你運行它時會發生什麼? – 2015-02-11 08:07:50

+0

如果您擺脫了「On Error GoTo」,可能會有更高的機會找到錯誤 – EngJon 2015-02-11 08:13:03

回答

2
Sub test() 

    Dim WbookCheck As Workbook 

    On Error Resume Next 
    Set WbookCheck = Workbooks("Weekly Report.xls") 
    On Error GoTo 0 

    If WbookCheck Is Nothing then 'not open.... 

     filepaths = "c:\clients\work\Weekly Report.xls" 

     If Dir(filepaths) = "" Then 
      MsgBox "Please save the latest file under the name" & _ 
       " 'US Sector Flow Weekly Report' and run the macro again" 
      Exit Sub 
     Else 
      'file exists - open it 
      Set WbookCheck = Workbooks.Open(filepaths) 
     End If 
    End If 

    with WbookCheck 
     .Activate 
     .Sheets("This week").Copy _ 
       Before:=Workbooks("Consolidated.xls").Sheets(1) 
    end with 

End Sub 
+0

,謝謝Tim和EngJon的回覆。非常感謝你的幫助。我會嘗試你給出的代碼。 – 2015-02-11 08:53:10

+1

@Manya你呢?它工作了嗎(當然蒂姆寫的!)?你見過http://stackoverflow.com/help/accepted-answer嗎? – pnuts 2015-10-01 05:47:32

相關問題