PDA

View Full Version : Solved: Word vba syntax



Mike100
01-12-2009, 08:33 AM
I've only just started using Word VBA so sorry if this is a dumb question, but why does the first sub below work, and the second one doesn't ??


Private Sub ReplaceText1
Dim MyRange As Range
Set MyRange = ActiveDocument.Range
' Delete all '[' symbols
With MyRange.Find
.Text = "["
.Replacement.Text = ""
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End Sub

Private Sub ReplaceText2
' Delete all ']' symbols
ActiveDocument.Range.Find.Text = "]"
ActiveDocument.Range.Find.Replacement.Text = ""
ActiveDocument.Range.Find.Wrap = wdFindContinue
ActiveDocument.Range.Find.Execute Replace:=wdReplaceAll
End Sub

TonyJollans
01-12-2009, 11:32 AM
Hi Mike,

It is not a dumb question. The reason for this is one that is often misunderstood, even by experienced people.

A Range is an Object that, like all objects, only exists as long as a reference (a pointer) to it is maintained within your code.

The Range Method of the Document object returns (put another way, creates and returns a pointer to) a Range.

The statement:
With ActiveDocument.Range
.. causes a Range object to be created, and maintains a pointer to it, until the statement:
End With
Thus, code between these two lines works on a single Range object, doing exactly as you expect it to do.

The statement:
ActiveDocument.Range.Find.Text = "]"
.. causes a Range object to be created, and sets the Find Text of that Range. As no pointer to the created Range is maintained, the Range is immediately destroyed, and .. the statement:
ActiveDocument.Range.Find.Replacement.Text = ""
.. causes another Range object to be created, and sets the Replacement Text of that Range. As no pointer to the created Range is maintained, the Range is immediately destroyed, and .. ...

fumei
01-12-2009, 12:41 PM
In other words, if you changed:
Private Sub ReplaceText2
' Delete all ']' symbols
ActiveDocument.Range.Find.Text = "]"
ActiveDocument.Range.Find.Replacement.Text = ""
ActiveDocument.Range.Find.Wrap = wdFindContinue
ActiveDocument.Range.Find.Execute Replace:=wdReplaceAll
End Sub



to:

Private Sub ReplaceText2
' Delete all ']' symbols
With ActiveDocument.Range.Find
.Text = "]"
.Replacement.Text = ""
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End Sub
it will work, as all the instructions are action on the ONE object - ActiveDocument.Range. More accurately, all the instructions are actions through the .Find method of ONE object - ActiveDocument.Range.

And I agree with Tony, it most certainly is NOT a dumb question. The concept (scope) is crucial.

There is variable scope - WHERE and WHEN a variable is existing and useable.

There is object scope - WHERE and WHEN an object is existing and useable.

Mike100
01-13-2009, 08:21 AM
Thanks for the lengthy explination guys (especially Tonys).

I had to read through it a couple of times to fully understand it, but I believe it makes sense to me now.

cheers again.
Mike.