更新时间:2022-11-04 10:26:05
如果不将引用添加到类型库,则不能使用该类型库中定义的早期绑定类型.
If you're not adding the reference to the type library, you can't use the early-bound types defined in that type library.
Dim wkbkXLBook As Excel.Workbook
Dim wkSheet As Excel.worksheet
Excel
是Excel类型库的程序名称,而Workbook
是在该库中定义的类的名称.与Worksheet
相同.由于未引用Excel,因此VBA无法解析这些类型,并且会出现编译错误.
Excel
is the programmatic name of the Excel type library, and Workbook
is the name of a class defined in that library. Same for Worksheet
. Since Excel isn't referenced, VBA can't resolve these types, and you get a compile error.
您需要使用后期绑定代码,即在黑暗中,没有 IntelliSense ,自动补全或参数quick-info,并且不要输入任何错误-以免遇到运行时错误438和1004.
You need to work with late-bound code, i.e. in the dark, without IntelliSense, autocompletion, or parameter quick-info, and without making any typos - lest you run into run-time error 438 and 1004.
后期绑定"是指在运行时已解析".每当您声明As Object
时,就会发生以下情况:
"Late-bound" means "resolved at run-time". Whenever you declare something As Object
, that's precisely what happens:
Dim wkbkXLBook As Object
Dim wkSheet As Object
除非引用Excel类型库,否则不能使用任何Excel类型.其中也包括任何xl*
常量.
You can't use any of the Excel types unless you reference the Excel type library. That includes any xl*
constant, too.
Dim Excel As Object
我强烈建议将此名称重命名为xlApp
.
I'd warmly recommend renaming this to e.g. xlApp
.
当心隐式对象引用:
Dim someRange As Object
Set someRange = xlApp.ActiveWorkbook.Worksheets("Sheet1").Range("A1")
上面的方法可以工作,但也会泄漏ActiveWorkbook
对象,其Worksheets
集合以及检索到的Worksheet
对象;即使执行了xlApp.Quit
和Set xlApp = Nothing
之后,这些泄漏的对象仍可以(并且经常做)阻止EXCEL.EXE
进程正确关闭:避免像这样使用双点引用对象.改为执行此操作:
The above will work, but will also leak the ActiveWorkbook
object, its Worksheets
collection, and the Worksheet
object retrieved; these leaked objects can (and often do) prevent the EXCEL.EXE
process from correctly shutting down, even after executing xlApp.Quit
and Set xlApp = Nothing
: avoid double-dot referencing objects like this. Do this instead:
Dim books As Object
Set books = xlApp.Workbooks
Dim wb As Object
Set wb = books("workbook name")
Dim wbSheets As Object
Set wbSheets = wb.Worksheets
Dim ws As Object
Set ws = wbSheets("sheet name")
Dim rng As Object
Set rng = ws.Range("A1")
每个涉及的对象都明确地作用于本地过程,一切都会好起来的.
With every object involved explicitly scoped to the local procedure, everything should be fine.