2

In one of my classes, I have a global private variable:

Private ie as InternetExplorerMedium

This is an object from the Microsoft Internet Controls Reference. The code compiles successfully assuming the reference is already enabled.

However, one piece of my code is actually enabling these references in the first place. I'm writing an excel add-in that will enable these references, do the main code block, then disable these references at the end. Relevant (pseudo-)code:

Private Sub addReferences()
    For Each reference...
        Application.VBE.ActiveVBProject.References.AddFromFile <reference>
    Next reference
End Sub

Let's assume the user has none of these references enabled in the first place. The script will then not compile, stating that the "User-defined type" InternetExplorerMedium is not defined. The error makes sense, of course.

Is there any way to avoid this compile error, knowing that the code will initially enable these references and thus the objects will exist? I'm expecting the answer to be no, but what alternatives are there?

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 1
    via late binding: `Set ie = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")` – Florent B. Feb 23 '18 at 13:11
  • Another relevant question I found: https://stackoverflow.com/questions/8842703/compile-error-during-workbook-open – TerryA Mar 06 '18 at 05:57

1 Answers1

1

An alternative will be to swap from Early to Late Binding. This means declaring the object as Object and dynamically creating an instance at runtime.

Dim objWord As Object
Set objWord = CreateObject("Word.Application")

Since the object will be of type Object you will will lose intellisense and the object's constant values will not be recognized, however you could replace them with their corresponding value or even better, declare them yourself.

objDoc.Close SaveChanges:=wdDoNotSaveChanges '<-- Compile error

Const wdDoNotSaveChanges As Long = 0
objDoc.Close SaveChanges:=wdDoNotSaveChanges '<-- OK
objDoc.Close SaveChanges:=0 '<-- OK

By doing so, you do not have to include any library references in VBE.

MSDN: CreateObject()

Kostas K.
  • 8,293
  • 2
  • 22
  • 28
  • Thanks for the answer. How do I then use `CreateObject` to create an `InternetExplorerMedium` object? I tried `CreateObject("InternetExplorerMedium")` but I assume that's not the right syntax – TerryA Feb 23 '18 at 11:11
  • I believe you need `CreateObject("InternetExplorer.Application")`. – Kostas K. Feb 23 '18 at 11:17
  • Sadly, I'm getting an error described here: https://stackoverflow.com/questions/30086425/excel-vba-method-document-of-object-iwebbrowser2-failed - and the solution suggests early binding. Seems like I need `InternetExplorerMedium` – TerryA Feb 23 '18 at 11:21
  • Sorry to hear that. Maybe another user has a better solution to suggest. – Kostas K. Feb 23 '18 at 11:25