2015-02-11 79 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

相关问题