agregson
asked on
How replace text with the contents of a variable
I can find and replace text using a macro but can't seem to figure out how to find text and replace it with the contents of a variable. I thought the following code would work but it doesn't. 'Plane' is the variable and 'Count' is a For-Next loop. So the first pass the replacement text would be the contents of Plane1, then Plane2, then Plane3 etc
.Replacement.Text = Plane & Count
ASKER
Thanks Graham but that isn't what I need. Basically what is happening is this:
Find "[text" & Count & "]" (so on first loop this is [text1])
Insert contents of filename:="file" & Count & ".txt"
Then find [MoreText] and replace with the contents of Plane & Count (so on first loop this is Plane1)
This will then loop until the For-Next is finished.
Hope this makes sense.
Find "[text" & Count & "]" (so on first loop this is [text1])
Insert contents of filename:="file" & Count & ".txt"
Then find [MoreText] and replace with the contents of Plane & Count (so on first loop this is Plane1)
This will then loop until the For-Next is finished.
Hope this makes sense.
Perhaps you need something like this:
Sub FindLoop()
Dim Count As Integer
Dim Limit As Integer
Dim rng As Range
Limit = 100
For Count = 1 To Limit
Set rng = ActiveDocument.Range
With rng.Find
.Text = "[text" & Count & "]"
If .Execute(Replace:=wdReplaceNone) Then
rng.InsertFile "file" & Count & ".txt"
rng.End = ActiveDocument.Range.End
.Text = "More Text"
.Replacement.Text = "Plane" & Count
If .Execute(Replace:=wdReplaceOne) Then
Else
MsgBox """More Text"" not found after ""[text" & Count & "]"""
Exit Sub
End If
Else
MsgBox """[text" & Count & "]"" not found"
Exit Sub
End If
End With
Next Count
End Sub
ASKER
Thanks Graham but I think this is the line I'm having problems with
.Replacement.Text = "Plane" & Count
Everytime the code loops this will replace text with Plane1, Plane2 etc, but Plane1, Plane2 etc are variables that could contain anything e.g.
Plane1 = Monitor
Plane2 = Hair Cut
Plane3 = 5050
So I need to be able to replace the text with the contents of the variable and not the variable name. Hope this makes sense.
.Replacement.Text = "Plane" & Count
Everytime the code loops this will replace text with Plane1, Plane2 etc, but Plane1, Plane2 etc are variables that could contain anything e.g.
Plane1 = Monitor
Plane2 = Hair Cut
Plane3 = 5050
So I need to be able to replace the text with the contents of the variable and not the variable name. Hope this makes sense.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
With ActiveDocument.Range.Find
.Text = "Some Text"
.Replacement.Text = Plane
.Execute Replace:=wdReplaceAll
End With