Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to Excel objects in Access VBA?

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)
like image 726
Pablo Avatar asked Apr 20 '11 10:04

Pablo


People also ask

How do I reference an object in Excel VBA?

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.

How do I reference in VBA?

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″)”.

How do I add a reference library in VBA?

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.

What does the Application object refer to in VBA?

The Application object refers to the active Microsoft Access application.


1 Answers

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.

like image 140
David-W-Fenton Avatar answered Sep 18 '22 12:09

David-W-Fenton