打开时 ActiveSheet 和 ActiveWorkbook 为空 Excel
ActiveSheet and ActiveWorkbook are empty when opening Excel
我正在尝试打开 Excel 并在不同时间使用多个 sheet 中的信息来自动化 Word 文档。
通过调试,从局部变量的状态来看,Excel似乎启动成功,Workbook对象也分配成功。但是,当“DB Schedules”worksheet 被激活时,ActiveSheet 变量保持为空并且无法使用 属性“Name”,而是抛出“Object Required”错误并跳转到 finally 块.
工作簿的路径和 sheet 的名称都是正确的,但即使在激活任意 sheet 之前,ActiveSheet 变量还是空的。已知 sheet 包含信息,我尝试使用多个文件来确定。
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
您无需激活 sheet 即可使用它
'Do some stuff with different sheets
With XLWorkbook.Worksheets("DB Schedules")
MsgBox .Name
MsgBox .Parent.Name
End With
我正在尝试打开 Excel 并在不同时间使用多个 sheet 中的信息来自动化 Word 文档。
通过调试,从局部变量的状态来看,Excel似乎启动成功,Workbook对象也分配成功。但是,当“DB Schedules”worksheet 被激活时,ActiveSheet 变量保持为空并且无法使用 属性“Name”,而是抛出“Object Required”错误并跳转到 finally 块.
工作簿的路径和 sheet 的名称都是正确的,但即使在激活任意 sheet 之前,ActiveSheet 变量还是空的。已知 sheet 包含信息,我尝试使用多个文件来确定。
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
您无需激活 sheet 即可使用它
'Do some stuff with different sheets
With XLWorkbook.Worksheets("DB Schedules")
MsgBox .Name
MsgBox .Parent.Name
End With