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

时间:2015-02-11 08:03:40

标签: excel vba excel-vba

我正在开发一个VBA程序,我需要做以下事情:

单击按钮(运行宏)时:

  1. 检查文件夹中是否存在MS EXCEL工作簿。如果没有,则给出“工作簿不存在”的消息,VBA程序应该结束。

  2. 如果存在工作簿,请检查工作簿是关闭还是打开。如果它已关闭,那么打开工作簿,VBA程序应该采取更加艰难的步骤。

  3. 如果工作表已打开,则激活工作簿,VBA程序应按步骤移动。

  4. 到目前为止我写过这篇文章,但它不起作用:

    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
    

1 个答案:

答案 0 :(得分:3)

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