Kinimod
Kinimod

Reputation: 166

Create Object for handling word on the fly (VBA)

I'm using VBA for creating an instance of word currently by adding a reference to the library, but this cause an issue, because there existing some machines without word.

This cause instantly a runtime error at startup on these machines. It's not possible to catch this error.

However, I try to create an object in VBA on the fly by something like this

Dim oWshShell As WshShell
Set oWshShell = New WshShell
' *** TEST  REGESTRY
Dim tmp As String
tmp = oWshShell.RegRead("HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Word\Options\PROGRAMDIR")
Debug.Print tmp

tmp = tmp + "winword.exe"

Dim oWord As Object
Set oWord = Shell(tmp)

But my problem is that oWord is not an Object of Word.Application. So how to handle this?

Would be nice to get available all functionalities like with Word.Application.

Upvotes: 1

Views: 345

Answers (1)

A.S.H
A.S.H

Reputation: 29332

You don't have to use a shell, use COM factory directly:

Function openWordApp() As Object
    On Error Resume Next
    Set openWordApp = CreateObject("Word.Application")
    If openWordApp Is Nothing Then
        msgBox "Word not installed on this machine"
    Else
        openWordApp.Visible = True
    End If
End Function

In the caller, check if the returned value Is Nothing.

Upvotes: 1

Related Questions