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
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.
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.
"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
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
I'd warmly recommend renaming this to e.g. xlApp
.
Watch out for implicit object references:
Dim someRange As Object
Set someRange = xlApp.ActiveWorkbook.Worksheets("Sheet1").Range("A1")
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.
CreateObject("Excel.Application")
instead of GetObject? – fbueckertExcel.xxxx
in variable declaration. As with Excel object, dim as object and try??? – Nathan_SavCreateObject
could be used in theIf Excel Is Nothing
branch, to create a new instance when an existing one doesn't exist – Mathieu Guindon