How do I set a range in Word while opening that file with VBA in Excel?
Dim wordApp As Word.Application Dim wordObject As Word.Document Dim wordRange As Word.Range Dim filePath As String Dim fileName As String filePath = "C:\Users\" fileName = "somename.docx" Set wordApp = CreateObject("Word.Application") With wordApp .Visible = True .Activate .WindowState = wdWindowStateNormal End With Set wordObject = wordApp.Documents.Open(filePath & fileName) Set wordRange = Documents(fileName).Sections(1).Range With wordRange 'code End With
The line causing trouble:
Set wordRange = Documents(fileName).Sections(1).Range
Regardless of the string I put in this returns
4160 runtime error “Bad File Name”
If I use
ActiveDocument instead of
Documents(), I get
4248 runtime error: “This command is not available because no document is open”.
The error persists even after opening multiple unsaved and saved Word docs whilst running the code, only to have the same error message show up.
Set wordRange = Documents(fileName).Sections(1).Range errors because Excel doesn’t know what
Documents is (or it resolves it to something other than
To fix that, you’d use (just as you did in the previous line)
Set wordRange = wordApp.Documents(fileName).Sections(1).Range
That said, you’ve already
Document(filepath & filename) to
wordObject, so use it:
Set wordRange = wordObject.Sections(1).Range
Also, Excel doesn’t know
wdWindowStateNormal, so a new
Variant variable is created (unless you have
Option Explicit, which you should, always) and assigned the default value
0. Which just happens to be the value of
Word.wdWindowStateNormal so no harm done, but the code is misleading.
To fix, use
.WindowState = 0 'wdWindowStateNormal
I’m curious about the way you’ve created the object. Using early binding but instead of creating
New Word.Application you use
- Was this an intentional decision?
- What is the benefit?