Insert a PDF into Excel with Visual Basic

Viewed 609

I'm writing a macro which allows the user to insert a PDF into a worksheet. The trouble is that different people have different versions of Adobe. This code works on my machine:

ActiveSheet.OLEObjects.Add(ClassType:="Acrobat.Document.DC", Link:=False, DisplayAsIcon:=False).Activate

But that code will produce an error on someone else's machine because he needs this:

ActiveSheet.OLEObjects.Add(ClassType:="AcroExch.Document.DC", Link:=False, DisplayAsIcon:=False).Activate

Notice the ClassTypes are different. Is there a way to check if a ClassType exists? I'd like to do something like this:

If Exists(ClassType("Acrobat.Document.DC")) Then
     ActiveSheet.OLEObjects.Add(ClassType:="Acrobat.Document.DC", Link:=False, DisplayAsIcon:=False).Activate
Else 
     ActiveSheet.OLEObjects.Add(ClassType:="AcroExch.Document.DC", Link:=False, DisplayAsIcon:=False).Activate
End If

Note: I can brute-force this by using On Resume Error Next, but that doesn't seem like the cleanest method.

1 Answers

It is perfectly normal to use On Error Resume Next for this purpose. Here is an example

Sub Sample()
    Dim objAcrobat As Object
    Dim objAcroExch As Object
    
    On Error Resume Next
    Set objAcrobat = CreateObject("Acrobat.Document.DC")
    Set objAcroExch = CreateObject("AcroExch.Document.DC")
    On Error GoTo 0
    
    If Not objAcrobat Is Nothing Then
        MsgBox "Acrobat found"
    Else
        MsgBox "Acrobat not found"
    End If
    
    If Not objAcroExch Is Nothing Then
        MsgBox "AcroExch found"
    Else
        MsgBox "AcroExch not found"
    End If
End Sub

Since I have both, I get "found" for both.

Your usage would be something like this

Sub Sample()
    Dim objAcrobat As Object
    Dim objAcroExch As Object
    
    On Error Resume Next
    Set objAcrobat = CreateObject("Acrobat.Document.DC")
    Set objAcroExch = CreateObject("AcroExch.Document.DC")
    On Error GoTo 0
    
    If Not objAcrobat Is Nothing Then
        ActiveSheet.OLEObjects.Add(ClassType:="Acrobat.Document.DC", _
                                   Link:=False, _
                                   DisplayAsIcon:=False).Activate
    ElseIf Not objAcroExch Is Nothing Then
        ActiveSheet.OLEObjects.Add(ClassType:="AcroExch.Document.DC", _
                                   Link:=False, _
                                   DisplayAsIcon:=False).Activate
    Else
       MsgBox "Abobe not installed"
    End If
End Sub
Related