PDA

View Full Version : Solved: Replace All count



mdmackillop
01-31-2006, 12:06 PM
Hi all,
When you run Find and Replace, a dialog box advises the number of replacements made. Can this number be returned by the VBA code as a variable?
Regards
MD

mdmackillop
01-31-2006, 12:21 PM
I found a solution here.
http://word.mvps.org/FAQs/MacrosVBA/GetNoOfReplacements.htm

fumei
01-31-2006, 06:03 PM
I would like to point out, regarding that link, that it is very easy to get a count of a word in a document with MUCH less code, and WITHOUT using Replace, and WITHOUT doing all that processing with the counting of characters. Bleeech, blaaack!Sub CountOfWords()
Dim iCount As Integer
Dim strIn As String
strIn = InputBox("Enter a word to count.")
With ActiveDocument.Content.Find
Do While (.Execute(FindText:=strIn, Forward:=True) _
= True) = True
iCount = iCount + 1
Loop
End With
MsgBox "There are " & iCount & " instances of the word " & strIn
End Sub

TonyJollans
02-01-2006, 05:11 AM
Just for fun, what about this?

Sub Macro1()
'
' Macro1 Macro
' Macro recorded 01/02/2006 by Egbert
'
Dim WasTracking As Boolean
Dim RevisionCount As Long

WasTracking = ActiveDocument.TrackRevisions
RevisionCount = ActiveDocument.Revisions.Count
ActiveDocument.TrackRevisions = True

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "anthill"
.Replacement.Text = "foible"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

RevisionCount = (ActiveDocument.Revisions.Count - RevisionCount) / 2
If Not WasTracking Then
WordBasic.AcceptAllChangesInDoc
ActiveDocument.TrackRevisions = False
End If
MsgBox "Word has completed its search of the document and has made " & _
RevisionCount & " changes"

End Sub

TonyJollans
02-01-2006, 05:19 AM
Straight after posting I realised this was incomplete. Even if Track Changes is Off there may be Revisions in the Document, so some extra code is needed to deal with that.

As it was only for fun in the first place, I leave you to do that for yourself.

fumei
02-01-2006, 11:14 AM
Nice one Tony.

mdmackillop
02-01-2006, 12:44 PM
Thanks Both,
I was using the search replace anyway so I thought the extra loop an unnecessary step, but time is not much of an issue here. I'll have a play with the Revisions method as well.
Gerry,
I was incorporating this in that XML tags question, but I've not had a response.
Regards
Malcolm

mdmackillop
02-08-2006, 12:25 PM
Hi Gerry,
My problem in counting was the inclusion of brackets, since I've now found out to use \<*\>, this makes life simpler.
Regards
Malcolm

(memo to self RTFM :banghead: )