What declarations I have to make in order to be able to use Excel objects and constants from my Access 2007 VBA script?
Dim wb As Workbook
or
Set objExcelApp = New Excel.Application
or
.Borders(xlEdgeBottom)
Option #1: Using The VBA Object Name. In this case, the syntax that you must use to refer to an object is “Collection_name(“Object_name”)”. In other words: #1: The name of the relevant collection (collection_name) goes first.
If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.
To add an object library reference to your projectSelect the object library reference in the Available References box in the References dialog box and choose OK. Your Visual Basic project now has a reference to the application's object library.
The Application object refers to the active Microsoft Access application.
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With