views:

27

answers:

1

Question

How do I access a public constant defined in another Excel workbook?

Setup

Workbook.xls

My VBA code runs in the current Excel workbook called "MyWorkbook.xls". It has some VBA code in it which reads a file name --"OtherWorkbook.xls in this case-- from cell "A1". Then, the code should read a constant defined in that other workbook and write it to cell "A2". Here is what my code looks like:

Sub GetValueFromOtherWorkbook()
    otherWorkbook = Range("A1").Value  ' Value = "OtherWorkbook.xls"

    Dim returnedValue As String

    ' Idea 1: Doesn't work
    Set returnedValue = OtherWorkbook.xls!Module1.MY_CONSTANT

    ' Idea 2: Doesn't work either
    Set returnedValue = Application.Run(otherWorkbook & "!Module1.MY_CONSTANT")

    Range("A2").Value = returnedValue ' MY_CONSTANT = "testValue"
End Sub

OtherWorkbook.xls

The second Excel workbook is called "OtherWorkbook.xls" as mentioned above. It has a VBA module called Module1. Module1 defines a public constant. The code looks like this:

Public Const MY_CONSTANT As String = "testValue"

Problem

The code from MyWorkbook.xls does not run, it returns the following error

Run-time error '424'

Object required

I don't quite know what to do with it even after reading the help documentation. In another context, I managed to call a routine in another workbook with this code:

otherWorkbookName = "OtherWorkbook.xls"
Application.Run (otherWorkbookName & "!Module1.SomeRoutine")

So, calling a routine works, but accessing a public constant does not.

Any ideas what I could try next?

+1  A: 

A code module is not an object that can be accessed like a worksheet.

You can access and manipulate it, but in order to do that you need to reference the Microsoft Visual Basic for Applications Extensibility library and allow access to the VBA project (Tools - Options - Security - Macro security - Trusted publishers - Trust access to VBA project), after which you can use the Workbook.VBProject property of the second workbook.

You don't need to do this. Instead you can create a reference to the other workbook: in VBA IDE, go Tools - References, click Browse and locate your workbook with the constant.

If that's no good, you can create a method in that workbook that only returns the value of the constant, and call it as you have demonstrated.

GSerg
@GSerg: Great answer, thanks. Yes, I also thought of writing a wrapper method as a last resort. I think I'll go with that workaround so I don't have to introduce any new references.
Lernkurve