简体   繁体   English

VBA ActiveSheet 和 ActiveWorkbook 为空 - 打开 Excel 时出现问题

[英]VBA ActiveSheet and ActiveWorkbook are empty - problem with opening Excel

I ama fresh starter in VBA, coming over from Python.我是 VBA 的新手,从 Python 过来的。 I am trying to open Excel and use information in multiple sheets at different times to automate a Word document.我正在尝试打开 Excel 并在不同时间使用多张工作表中的信息来自动化 Word 文档。 Judging by the status of the local variables throughout debugging, Excel seems to launch successfully and the Workbook object is also assigned successfully.从整个调试过程中局部变量的状态来看,Excel似乎启动成功,Workbook对象也分配成功。 However, when the "DB Schedules" worksheet is activated, the ActiveSheet variable remains empty and fails to use the property "Name", instead throwing an "Object Required" error and jumping to the finally block.但是,当“DB Schedules”工作表被激活时,ActiveSheet 变量保持为空并且无法使用属性“Name”,而是抛出“Object Required”错误并跳转到 finally 块。 The path of the workbook and the name of the sheet are both correct, yet even before activating an arbitrary sheet the ActiveSheet variable is empty.工作簿的路径和工作表的名称都是正确的,但即使在激活任意工作表之前,ActiveSheet 变量也是空的。 The sheet is known to contain information, and I have tried with multiple files just to be sure.已知该工作表包含信息,为了确定起见,我尝试了多个文件。 Below is the code to replicate the problem.下面是复制问题的代码。 Thanks!谢谢!

Sub CompileReport()

    Dim XLInstance As Object
    Dim XLWorkbook As Object
    Dim XLPath As String

    XLPath = "C:\Users\SaracchiG\OneDrive - AECOM\Documents\M11 Jn7A\GC300 Certificates\" & _
    "Construction Compliance\Certificates Data Project_Name.xlsx"

    On Error Resume Next
    Set XLInstance = GetObject(, "Excel.Application")
    XLInstance.Quit
    If Err Then
        Set XLInstance = CreateObject("Excel.Application")
    End If
    On Error GoTo Finally
    Set XLWorkbook = XLInstance.Workbooks.Open(XLPath, ReadOnly:=True)
  
    'Testing it all works (doesn't!)
    XLWorkbook.Worksheets("DB Schedules").Activate
    MsgBox ActiveSheet.Name
    MsgBox ActiveWorkbook.Name
    'Do some stuff with different sheets

    Finally:
        XLWorkbook.Close
        XLInstance.Quit

End Sub

You don't have to activate the sheet to work with it您不必激活工作表即可使用它

    'Do some stuff with different sheets
    With XLWorkbook.Worksheets("DB Schedules")
           MsgBox .Name
           MsgBox .Parent.Name
    End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM