I am trying to replace text in a word document from the entries in Excel. When I run the code without the tag for-loop (that means with single tag-value combination) it works as normal. But, I insert the wdDoc.StoryRanges loop inside the outer tags loop I am getting the error
"Object variable or with block variable not set"
despite setting the wdDoc value before the outer loop.
Can any of you please advise.
Thank you very much!
Public Function Test(filepath as String) As Variant
counter = 0
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("word.application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Open(filePath)
For Each tag In tags
counter = counter + 1
If Len(tag) > 0 Then
Dim wdRng As Word.Range
For Each wdRng In wdDoc.StoryRanges <-- [I am getting the error here]
With wdRng.Find
.Text = tag
.Highlight = True
With .Replacement
.Text = values(counter, 1)
.Highlight = False
End With
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Set wdApp = Nothing: Set wdDoc = Nothing: Set wdRng = Nothing
Next wdRng
End If
Next tag
End Function
StoryRangesisn't set? Is the file actually opening?Option Expliciton top of your code see Option Explicit Statement (Visual Basic)