PDA

View Full Version : [SOLVED:] Macro for finding en dash surrounded by text without spaces



rook
02-15-2020, 08:34 AM
Hello,

I’m trying to create macro in Word that would find and highlight only following scenario:

anyText–anyText

(word, no space, en dash, followed by another word without space).

in fact, even that would be enough:

anyLetterEndingString–anyLetterStartingString

I need to be able to locate en dash when it's surrounded by text without spaces.

I will be very grateful for any tips, since I'm stuck...

----

Here's the last of my attempts, just for reference:


Sub Testt()


Set r = ActiveDocument.Range
With r.Find
.ClearFormatting
.Text = "(< *)(^0150)(* >)"
.MatchWildcards = True
Do While .Execute(Forward:=True) = True
r.HighlightColorIndex = wdPink
Loop
End With






End Sub






Best regards

Paul_Hossler
02-15-2020, 09:44 AM
Try this

I'm pretty sure that the Word VBA gurus that hang out here can improve it, but it seems to work





Option Explicit


Sub Test2()

With Selection

.HomeKey Unit:=wdStory

.Find.ClearFormatting

.Find.Text = "[! ]^=[! ]"
.Find.Forward = True
.Find.Wrap = wdFindContinue
.Find.MatchWildcards = True

Do While .Find.Execute(Forward:=True)
.MoveLeft Unit:=wdCharacter, Count:=1
.MoveRight Unit:=wdCharacter, Count:=1
.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
.Range.HighlightColorIndex = wdPink
.MoveRight Unit:=wdCharacter, Count:=1
Loop

End With
End Sub

rook
02-18-2020, 05:36 AM
Try this

I'm pretty sure that the Word VBA gurus that hang out here can improve it, but it seems to work





Option Explicit


Sub Test2()

With Selection

.HomeKey Unit:=wdStory

.Find.ClearFormatting

.Find.Text = "[! ]^=[! ]"
.Find.Forward = True
.Find.Wrap = wdFindContinue
.Find.MatchWildcards = True

Do While .Find.Execute(Forward:=True)
.MoveLeft Unit:=wdCharacter, Count:=1
.MoveRight Unit:=wdCharacter, Count:=1
.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
.Range.HighlightColorIndex = wdPink
.MoveRight Unit:=wdCharacter, Count:=1
Loop

End With
End Sub



Thank you, that works perfectly!

macropod
02-18-2020, 02:16 PM
I'm pretty sure that the Word VBA gurus that hang out here can improve it, but it seems to work

Indeed:

Sub DSFinder()
Application.ScreenUpdating = False
Dim iDx As Long
iDx = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdPink
With ActiveDocument.Range.Find
.MatchWildcards = True
.Text = "<[! ]@^=*>"
.Replacement.Text = "^&"
.Replacement.Highlight = True
.Execute Replace:=wdReplaceAll
End With
Options.DefaultHighlightColorIndex = iDx
Application.ScreenUpdating = True
End Sub
Cross-posted (and answered) at: https://stackoverflow.com/questions/60240033/how-to-find-word-with-en-dash-within-it/60242737#60242737
@rook: Kindly read VBA Express' policy on Cross-Posting in Rule 3: http://www.vbaexpress.com/forum/faq.php?faq=new_faq_item#faq_new_faq_item3

rook
02-18-2020, 02:28 PM
Thank you, will keep in mind for the future.