1

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
2
  • 1
    I'm guessing StoryRanges isn't set? Is the file actually opening? Commented Jan 25, 2018 at 21:06
  • 1
    Use Option Explicit on top of your code see Option Explicit Statement (Visual Basic) Commented Jan 25, 2018 at 21:46

1 Answer 1

1

That error usually means the variable is not set. if you add a watcher at the wdDoc.StoryRanges you might see if that variable is set or not. Or even possible wdRng is not set, Then you might have to use a counter Index, and use while loop to do your task.

Sign up to request clarification or add additional context in comments.

1 Comment

With few iterations, I realized that wdRng did not set. I had to create another variable in side the for-loop and sRng and set it to wdRng.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.