Why VBA command documents.open doesn't works on first run? - excel

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

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.

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.

Related

Export Excel Range to Word

From Excel using VBA I want to copy a range from Excel to Word and I'm stuck!
I'm trying to recreate what I do manually by:
Select a Range of cells and COPY
Open a Word Doc
Select "Paste Special" and "Formatted Text (RTF)"
I've tried multiple versions of code that I've found on the internet but I am unable to get the code to run. I do have the "Microsoft Word 16.0 Object Library" Checked as a reference in Excel.
The Error I get is "Run Time Error 91 - Object Variable or With Block Variable not set". I have marked in the code below where it fails. When I run this it launches Word but it does not open a new document.
Here's the code that has gotten me the farthest.
Sub ExcelToWord()
Dim PageNumber As Integer
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim FileToOpen As String
Dim strPath As String
FileToOpen = "Excel Link test.docx"
strPath = "C:\"
'the next line looks to a cell to decide what page number to scroll to
PageNumber = 1 'Later
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
Else
On Error GoTo notOpen
Set wrdDoc = wrdApp.Documents(FileToOpen)
GoTo OpenAlready
notOpen:
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
End If
OpenAlready:
On Error GoTo 0
Range("A6:D11").Copy ' med WS Name
With wrdApp
'------> Fails Here
.Selection.Goto What:=1, Which:=2, Name:=PageNumber
.Visible = True
.Selection.Paste
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
As always, thanks for your help!
Please, test the next code. It will open a new blank document and use it instead of the one being open by code:
Sub ExcelToWord()
Dim PageNumber As Integer, wrdApp As Word.Application, wrdDoc As Word.Document
Dim sh As Worksheet
Set sh = ActiveSheet 'use here the sheet you need
PageNumber = 1
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
err.Clear: On Error GoTo 0
Set wrdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wrdDoc = wrdApp.Documents.Add 'add a blank document
wrdApp.Visible = True 'make Word application visible
'only for debugging, if not want to be visible
'and you will save it (programmatically) in the next steps...
sh.Range("A6:D11").copy ' med WS Name
With wrdApp
.Selection.Goto What:=1, which:=2, Name:=PageNumber
.Visible = True
.Selection.Paste
End With
Set wrdDoc = Nothing: Set wrdApp = Nothing
End Sub

Rule Word Sections in Excel VBA

I want to control footer in Word file via Excel VBA.
Dim objWord
Dim objDoc
Dim Sec
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set Sec = objDoc.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.Add
I get "Object does'not support this property or method." alert
Where am I wrong.Please help.
Add the Microsoft Word XX.0 Object Library (I am on 16) from Tools > References in the VBA IDE
Sub createWordAddFooter()
Dim objWord As Word.Application
Dim objDoc As Word.Document
Set objWord = New Word.Application
Set objDoc = objWord.Documents.Add
objWord.Visible = True
objDoc.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.Add
End Sub

Inserted Word Table not showing Borders

I can insert a table but the tables borders are not visible. You can see the created document. In order to allow others to run this script I have to use late binding which I suspect may be the cause.
My Code is here:
Sub Button1_Click()
Dim objWord As Object
Dim objDoc
Dim objSelection
Dim i As Long
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
objSelection.TypeText ("Insert table after this text")
Set myRange = objDoc.Content
myRange.Collapse Direction:=wdCollapseEnd
objDoc.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=4
Set myTable = objDoc.Tables(1)
With myTable.Borders
.Enable = True
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleDouble
.InsideColor = wdColorBlack
.OutsideColor = wdColorBlack
End With
End Sub
Here’s your code revised and in my testing it works when I run it from Excel.
Sub Button1_Click()
Dim objWord As Object
Dim objDoc As Object
Dim objSelection As Object
Dim i As Long
Dim myRange As Object
Dim myTable As Object
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
Set objWord = CreateObject("Word.Application")
End If
objWord.Visible = True
On Error GoTo 0
Set objDoc = objWord.Documents.Add
Set objSelection = objWord.Selection
objSelection.TypeText ("Insert table after this text")
Set myRange = objDoc.Content
myRange.Collapse Direction:=wdCollapseEnd
Set myTable = objDoc.Tables.Add(Range:=myRange, NumRows:=3, NumColumns:=4)
With myTable.Borders
.Enable = True
.InsideLineStyle = 1
.OutsideLineStyle = 7
.InsideColor = 0
.OutsideColor = 0
End With
End Sub
The issue with with the table borders not displaying is when using late binding you have to use the numeric values for the setting.
I also made a few other adjustments, they have no impact on the problem you were having, but they are better practices. All objects are declared and I added a test to see if the Word application was already running. In some releases of the Office applications, multiple instances of the application could get loaded into memory when you execute a CreateObject and the application was already there.

Altering Word view from Excel VBA

I'd like to change the view in Word from my Excel macro (which creates the Word document).
I'd like to execute: ActiveWindow.View.Type = wdWebView
In my Excel macro, I have:
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
As mentioned in the comments, you're mixing late-binding and early-binding, and also need to reference the Word instance.
An early-binding approach might be (add a reference to the Microsoft Word xx.0 Object Library under Tools > References).
Sub MyWord()
Dim wordApp As New Word.Application
Dim myDoc As Word.Document
wordApp.Visible = True
Set myDoc = wordApp.Documents.Add
wordApp.ActiveWindow.View.Type = wdWebView
End Sub
If you want to late-bind, note from the WdViewType enum docs that wdWebView corresponds to the value 6.
Sub MyWord()
Const wdWebView As Long = 6
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add
objWord.ActiveWindow.View.Type = wdWebView
End Sub
You don't have to use early binding to use wdWebView. Instead, you could use:
Dim objWord As Object, objDoc As Object
Const wdWebView As Long = 6
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.ActiveWindow.View.Type = wdWebView

Excel VBA to Open Multiple Word 2010 Documents and Determine if Checkboxes are Checked

I'm trying to create a report that analyzes multiple word documents in a folder and analyzes checkboxes in the document to determine if a set of tests passed or failed. I have code that loops through all documents in a folder, but I'm having a hard time determining how to determine if the boxes are checked.
The first checkbox I'm trying to evaluate is tagged "PassCheckBox". I've found several articles with syntax on how to do this, but none seem to work with the way I'm iterating through the word files. My current code give me "Object is Required" when I try to run.
Here is my current code:
Sub ParseTestFiles()
Dim FSO As Object
Dim fPath As String
Dim myFolder, myFile
Dim wdApp As Object
Dim PassValue As Boolean
fPath = ActiveWorkbook.Path
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = FSO.GetFolder(fPath).Files
For Each myFile In myFolder
If LCase(myFile) Like "*.doc" _
Or LCase(myFile) Like "*.docx" Or LCase(myFile) Like "*.docm" Then
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word not yet running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
' Here is where I'm having an issue
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked
Set wdApp = Nothing
End If 'LCase
Next myFile
End Sub
Try to use:
Dim c, wdDoc
Set wdDoc = wdApp.Documents.Open(CStr(myFile))
wdApp.Visible = True
For Each c In wdDoc.ContentControls
If c.Title = "PassCheckBox" Then
PassValue = c.Checked
Exit For
End If
Next
instead
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked

Resources