How to reference an Object library in VBA Excel when the installed version may vary between different users?

83 views Asked by At

I need to use a ChemDrawCtl object in one of my projects. So far I have used early binding by referencing the library "CD ChemDraw 20.0 Object Library" which have worked well so far. However, I have now been forced to make the code more portable and the installed version of this object library may differ between different users. I have found a "dirty" way to accomplish this via late binding, but it is, so to say, very non-elegant. Is there a better, more correct way to accomplish this? Example code:

Option Explicit

Function NewChemDrawCtl() As Object
    Dim i As Long
    Static v As Long
    On Error Resume Next
    If v = 0 Then
        For i = 50 To 12 Step -1
            Set NewChemDrawCtl = CreateObject("ChemDrawControl" & i & ".ChemDrawCtl")
            If TypeName(NewChemDrawCtl) = "ChemDrawCtl" Then
                v = i
                Exit For
            End If
        Next
    Else
        Set NewChemDrawCtl = CreateObject("ChemDrawControl" & v & ".ChemDrawCtl")
    End If
End Function
0

There are 0 answers