I am trying to open a word .docm via a string with Documents.Open. It works after the second run of the script. In the first run the document simply doesn't open up, and the script doesn't load the doc file. Any thoughts or tips?
Sub gerarproposta()
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Dim objWord As Word.Application, wdDoc As Word.Document
'banco de dados
Dim xl As New Excel.Application
Dim xlw As Excel.Workbook
'Variável texto
Dim Tex As String
On Error Resume Next
Set basedados = Sheets("Base de Dados")
Set objWord = GetObject(, "Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
'xl.Visible = True
'Word - proposta modelo
Tex = """" & basedados.Range("B30") & "\" & basedados.Range("B31") & """"
'Abre o arquivo do Word
Set wdDoc = objWord.Documents.Open(Tex)
.
.
.
End Sub
- Already tried to change the TEX variable to a String manually
- Every run after the first one works normally
CodePudding user response:
The commentary of @Shrotter solved my problem. I changed the code:
Set objWord = GetObject(, "Word.Application")
To:
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
I tried to get the object from a non-existent Word session.
CodePudding user response:
The following statement for retrieving the Word Application
instance can be used if Word is already launched:
Set objWord = GetObject(, "Word.Application")
Instead, you could an early binding like you did in case of Excel:
Set objWord = New Word.Application
Read more about early and late binding technology in the Early and Late Binding (Visual Basic) article.