检查工作簿是否存在,如果存在则检查其是否打开。如果打开则激活,如果关闭则打开

Man*_*han 0 excel vba

我正在开发一个 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
Run Code Online (Sandbox Code Playgroud)

Tim*_*ams 5

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
Run Code Online (Sandbox Code Playgroud)