问题是您正在使用早期绑定。您必须使用后期绑定。
在早期绑定中,您设置了对 Excel 对象 xx.xx 库的引用,而在后期绑定中您没有。
这是两者的示例
早期绑定
Sub EarlyBindingEx()
Dim oXLApp As Excel.Application
Dim oXLWb As Excel.Workbook
Dim oXLWs As Excel.Worksheet
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = New Excel.Application
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open files
Set oXLWb = oXLApp.Workbooks.Open("C:\Sample.xlsx")
'~~> Set the relevant worksheet
Set oXLWs = oXLWb.Sheets(1)
'
'~~> Rest of your code
'
End Sub
后期装订
Sub LateBindingEx()
Dim oXLApp As Object
Dim oXLWb As Object, oXLWs As Object
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open files
Set oXLWb = oXLApp.Workbooks.Open("C:\Sample.xlsx")
'~~> Set the relevant worksheet
Set oXLWs = oXLWb.Sheets(1)
'
'~~> Rest of your code
'
End Sub
这里是关于早期绑定与后期绑定的 MSDN 链接。