How to open Word Application using vba

*爱你&永不变心* 提交于 2021-02-07 10:28:06

问题


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


回答1:


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



回答2:


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



回答3:


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?



来源:https://stackoverflow.com/questions/47158574/how-to-open-word-application-using-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!