Hi Luca,
In a lot of cases, it's much quicker and easier to use Find/Replace,
especially with wildcards, than to check each possible occurrence in
sequence. For some background, you should read
http://www.gmayor.com/replace_using_wildcards.htm and
http://www.word.mvps.org/FAQs/MacrosVBA/BatchFR.htm.
That said, there are some quirks in Word's Find/Replace that need to be
worked around. One is that if the range to be searched exactly matches the
term you're searching for, Word won't find it. :-( Bug city. Another is that
it sometimes isn't possible to limit the Find to just the selected text, so
it becomes necessary to check each found item to make sure it's within the
original selection.
The following assumes that each "line" is really a paragraph, ending witha
paragraph mark (character 13, shown in nonprinting characters as ¶) andnot
a manual line break or something else. For Fortran code that's probably a
good assumption.
Sub AddBang()
Dim oRg As Range
Set oRg = Selection.Range
With oRg.Find
.MatchWildcards = True
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([!^13]{1,}^13)"
.Replacement.Text = "!\1"
.Wrap = wdFindStop
.Execute Replace:=wdReplaceAll
End With
Set oRg = Nothing
End Sub
Sub RemoveBang()
Dim oRg As Range
Dim oRgOrig As Range
Set oRg = Selection.Range
Set oRgOrig = Selection.Range
' If the selection is exactly one
' paragraph starting with a !
' then .Execute won't find it.
' Handle this case first.
If (oRg.Paragraphs.Count = 1) And _
(oRg.Characters(1).Text = "!") Then
oRg.Characters(1).Delete
Else
With oRg.Find
.MatchWildcards = True
.ClearFormatting
.Replacement.ClearFormatting
.Text = "(\!)([!^13]{1,}^13)"
.Wrap = wdFindStop
Do While .Execute
If oRg.InRange(oRgOrig) Then
oRg.Characters(1).Delete
oRg.Collapse wdCollapseEnd
End If
Loop
End With
End If
Set oRg = Nothing
Set oRgOrig = Nothing
End Sub
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroupso
all may benefit.
Hi all,
I am an absolute beginner concerning VBA and seeking a solution to a
problem a VBA crack may solve in a few minutes. The problem is as
follows:
I need a macro that is able to put a "!" in front of each line of a
selected text. Another macro should be able to remove that "!" again,
that means it must check every line if there is a "!" as first
character and remove it.
I need these two macros to comment out Fortran code without having to
insert/remove "!" manually which is very tedious when dealing with
thousands of command lines.
Can someone help me?
Thanks,
Luca