Reputation: 2298
I'm trying to replace all Left and Right double angle quotes
chr(171) and chr(187) followed by a space chr(32) that is «
or »
with only the chr(171) or chr(187) respectively.
Replace this "« Abc" for this "«Abc"
and
Replace this "xyz »" for this "xyz»"
I´m using the code below, but after the replacement, the character is a double quote “
instead a double angle quote «
Sub ReplaceDoubleAngleQuotes()
With Selection.Find
.ClearFormatting
.Text = Chr(171) & Chr(32)
.Replacement.ClearFormatting
.Replacement.Text = Chr(171)
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
How to fix this? Thanks in advance.
Upvotes: 2
Views: 266
Reputation: 78185
First of all, Chr(171)
and Chr(187)
are not angle quotes. They might be on certain locales, but on others they will be different characters. You want to use ChrW(171)
and ChrW(187)
.
With that in mind, your code actually works and correctly replaces the quote, but then Word's File - Options - Proofing - AutoCorrect options - AutoFormat As You Type - Straight quotes with smart quotes kicks in and replaces the final «
with “
.
One option is to disable that feature:
Dim prev_value As Boolean
prev_value = Application.Options.AutoFormatAsYouTypeReplaceQuotes
Application.Options.AutoFormatAsYouTypeReplaceQuotes = False
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Execute FindText:=ChrW$(171) & " ", _
ReplaceWith:=ChrW$(171), _
Replace:=wdReplaceAll, _
Forward:=True, _
Wrap:=wdFindContinue
End With
Application.Options.AutoFormatAsYouTypeReplaceQuotes = prev_value
Another option is to use wildcard matching, capture the anlge quote as a separate group and mention it in the replacement wildcard:
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Execute FindText:="(" & ChrW$(171) & ")( )", _
MatchWildcards:=True, _
ReplaceWith:="\1", _
Replace:=wdReplaceAll, _
Forward:=True, _
Wrap:=wdFindContinue
End With
For some reason the smart quote feature does not kick in in this case.
Upvotes: 1
Reputation: 2016
Probably You got turned on .AutoFormatAsYouTypeReplaceQuotes
and your Word is changing chr(171) («) into "".
If You want to just turn this off for function Find&Replace do sth like:
Sub ReplaceDoubleAngleQuotes()
Dim userSmartQuotes As Boolean
userSmartQuotes = Options.AutoFormatAsYouTypeReplaceQuotes
Options.AutoFormatAsYouTypeReplaceQuotes = False
With Selection.Find
.ClearFormatting
.Text = Chr(171) & Chr(32)
.Replacement.ClearFormatting
.Replacement.Text = Chr(171)
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
Options.AutoFormatAsYouTypeReplaceQuotes = userSmartQuotes
End Sub
If You want to just turn this off (without returning to main setting) put
Options.AutoFormatAsYouTypeReplaceQuotes = False
at the beginning and that is all.
Upvotes: 3