How to open Word Application using vba

Viewed 18738

I have a code. It does not run in 2016.Is it a Office 16 problem

Dim objWordApp as Word.Application
Dim objWordDoc as Word.document
Set objWordApp = new Word.application

I get an error Error in loading DLL .I have already included the library Microsoft word 16.0 Object Library

regards Anna

3 Answers

I am not sure what went wrong for you but if you just want to open a new word document with your default MS office then you can use this peace of code

Sub wordopener()
  Dim objWord
  Dim objDoc
  Set objWord = CreateObject("Word.Application")
  Set objDoc = objWord.Documents.Add
  objWord.Visible = True
End Sub

I generally have a BAS file containing the 'CreateWord' function which I drag into any workbook/database that needs it.

First it tests to see if Word is already open using GetObject. If that returns an error it creates an instance of Word using CreateObject.

The Word application can then be opened by simply using Set oWD_App = CreateWord.

Sub Test()

    Dim oWD_App As Object
    Dim oWD_Doc As Object

    Set oWD_App = CreateWord

    With oWD_App
        Set oWD_Doc = .Documents.Add
    End With

End Sub


Public Function CreateWord(Optional bVisible As Boolean = True) As Object

    Dim oTempWD As Object

    On Error Resume Next
    Set oTempWD = GetObject(, "Word.Application")

    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo ERROR_HANDLER
        Set oTempWD = CreateObject("Word.Application")
    End If

    oTempWD.Visible = bVisible
    Set CreateWord = oTempWD

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure CreateWord."
            Err.Clear
    End Select

End Function

You are trying to use early binding. It is advisable, because it is a bit faster and it gives you intellisense, which is nice. However, to use it, you should add the corresponding libraries.

However, if you use the slower late binding, you do not need to add any libraries. It does not have intellisense and it would be a bit slower (but probably not noticeable).

Try like this:

Option Explicit

Sub TestMe()

    Dim objWord As Object
    Dim objDoc  As Object

    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Add
    objWord.Visible = True

End Sub

Early binding vs. late binding: what are the comparative benefits and disadvantages?

Related