Word VBA Find
This example is a simple word macro find the text “a”:
Sub SimpleFind()
Selection.Find.ClearFormatting
With Selection.Find
.Text = "a"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
End Sub
Find and Replace
This simple macro will search for the word “their” and replace it with “there”:
Sub SimpleReplace()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "their"
.Replacement.Text = "there"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
Find and Replace Only in Selection
This VBA macro will find and replace text in a selection. It will also italicize the replaced text.
Sub ReplaceInSelection()
'replaces text JUST in selection . in adittion it makes replaced text italic
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "their"
With .Replacement
.Font.Italic = True
.Text = "there"
End With
.Forward = True
.Wrap = wdFindStop 'this prevents Word from continuing to the end of doc
.Format = True 'we want to replace formatting of text as well
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
This line of code prevents VBA from continuing to the end of the Word document:
.Wrap = wdFindStop 'this prevents Word from continuing to the end of doc
This line of code indicates to replace the formatting of the text as well:
.Format = True 'we want to replace formatting of text as well
Find and Replace Only In Range
Instead of replacing text throughout the entire document, or in a selection, we can tell VBA to find and replace only in range. In this example we defined the range as the first paragraph:
Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
Sub ReplaceInRange()
'replaces text JUST in range [in this example just in the first paragraph]
Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
oRange.Find.ClearFormatting
oRange.Find.Replacement.ClearFormatting
With oRange.Find
.Text = "their"
.Replacement.Text = "there"
.Forward = True
.Wrap = wdFindStop 'this prevent Word to continue to the end of doc
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
oRange.Find.Execute Replace:=wdReplaceAll
End Sub
By using Replace and Split, this was easily accomplished.
Option Explicit
Public Sub StringInString()
Dim myString As String: myString = "This is my string. {This is another string.} How do I go about searching through this?"
Dim findString As String: findString = "this"
Dim var As Variant, mySplit As Variant
Dim matchCount As Integer: matchCount = 0
' Remove any characters that aren't pure text, but leave spaces so we can split on those.
Dim removeChars: removeChars = Array(".", ",", "/", "", "|", "{", "}", "[", "]", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", ":", ";", """", "'", "<", ">", "?", "`", "~")
For Each var In removeChars
myString = Replace(myString, var, vbNullString)
Next
mySplit = Split(myString, " ")
For Each var In mySplit
If (LCase(findString) = LCase(var)) Then matchCount = matchCount + 1
Next
End Sub
I don’t quite know what it is you’re expecting as your output, so modify as needed.
EDIT:
Even simpler solution, using Regular Expressions (required reference to Micrsoft VBScript Regular Expressions 5.5):
Public Sub StringInStringRegex()
Dim myString As String: myString = "This is my string. {This is another string.} How do I go about searching through this?"
Dim reg As New RegExp
reg.Pattern = "(this)"
reg.Global = True
reg.IgnoreCase = True
reg.MultiLine = True
Dim Matches As MatchCollection
Set Matches = reg.Execute(myString)
Dim matchCount As Integer: matchCount = Matches.Count
End Sub
Sources: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops and Pattern match count in excel (regex & vba)
- Remove From My Forums
-
Вопрос
-
When I do a Selection.find using wildcards, it returns a number of corresponding words. Are those words automatically a Collection? I want to create a list of unique words found at the end of the document with no duplicates in the list (yes, I know that’s
a tautology!) — would that require a dictionary function?-
Изменено
6 февраля 2014 г. 13:52
-
Перемещено
Jeffrey_Chen_
10 февраля 2014 г. 5:52
word development question
-
Изменено
Ответы
-
Hi,
Based on my understanding, Did you want get all of the unique words from a document and create list with these words.
If so , you can just set wildcards to «?*[ |,|.|;|’|:|?]» like below:
Sub Main() Dim List As New Collection Dim r As Range Set r = ActiveDocument.Range r.Select With Selection.Find .ClearFormatting .text = "?*[ |,|.|;|'|:|?]" .Forward = True .Wrap = wdFindStop .MatchWildcards = True .MatchCase = False .MatchWholeWord = False .MatchAllWordForms = False .MatchSoundsLike = False .MatchWildcards = True End With Do While Selection.Find.Execute Dim strResult As String strResult = Left(Selection.text, Len(Selection.text) - 1) If (Not IsContainValue(List, strResult)) Then List.Add (strResult) End If Loop End Sub Function IsContainValue(List As Collection, text As String) As Boolean For Each Item In List If (Item = text) Then IsContainValue = True Exit Function End If Next Item IsContainValue = False End Function
This sample code can find all of words in document and save these to List collection.
Regards,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.-
Помечено в качестве ответа
sluice
11 февраля 2014 г. 10:20
-
Помечено в качестве ответа
02-04-2014, 12:33 AM |
|||
|
|||
How to find and select text in a document? I’m trying to create a Word 2010 macro that finds, selects, and reformats a single word in my document starting from the current cursor position. During recording of the macro, I’ve tried to use Find in the menu (Ctrl-F) but nothing is recorded in my macro for the find operation even though the cursor moves and highlights the found word. I’ve tried using the code below but that is also not moving the current cursor position to this word. Can somebody tell me how to record a Find text operation in a Word macro or else tell me what the correct VBA code is to do this? Thanks in advance! Selection.Find.Text = «Synposis»
Selection.Font.Bold = wdToggle |
02-04-2014, 06:53 PM |
Your code suggests you want to toggle the bold attribute for ‘Synopsis’ in the ‘Body Text’ Style, not simply make it all bold or all not bold. In that case, you could use a macro like: Code: Sub Demo() Application.ScreenUpdating = False Dim Rng As Range With Selection Set Rng = .Range With .Find .ClearFormatting .Replacement.ClearFormatting .Text = "Synopsis" .Replacement.Text = "^&" .Style = "Body Text" .Forward = True .Wrap = wdFindStop .Format = True .MatchCase = True .MatchWholeWord = True .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute End With Do While .Find.Found .Font.Bold = wdToggle .Collapse wdCollapseEnd .Find.Execute Loop End With Rng.Select Set Rng = Nothing Application.ScreenUpdating = True End Sub If, however, you wish to make all such text bold, the macro could be made much more efficient and simplified to: Code: Sub Demo() Application.ScreenUpdating = False With Selection With .Find .ClearFormatting .Replacement.ClearFormatting .Text = "Synopsis" .Replacement.Text = "^&" .Style = "Body Text" .Replacement.Font.Bold = True .Forward = True .Wrap = wdFindStop .Format = True .MatchCase = True .MatchWholeWord = True .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll End With End With Application.ScreenUpdating = True End Sub If you want to make the font not bold instead, change:
__________________ |
02-04-2014, 07:02 PM |
|||
|
|||
Thanks. Does the code have to be this complicated? All I want to do is find the next word «Synopsis» after the current cursor position and change it’s style to Body Text and make it bold face. |
02-04-2014, 07:26 PM |
No, it doesn’t ‘have’ to be so complicated, but leaving out some parameters might lead to unexpected results … Re: Quote: change it’s style to Body Text and make it bold face That’s not what the code I posted does. Based on what you had posted, the code I posted looks for ‘Synopsis’ that is already in the ‘Body Text’ Style. Furthermore, you can’t re-format only a single word of many in a paragraph with the ‘Body Text’ Style, as that Style is a paragraph Style. Of course, that doesn’t matter if ‘Synopsis’ is the only word in the paragraphs concerned. As for changing the font to bold, if ‘Synopsis’ is the only word in the paragraphs concerned, you’d do better to change the ‘Body Text’ Style’s font to bold than to override the Style format. Similarly, if ‘Synopsis’ is only one word of many in a paragraph, you’d do better to apply the ‘Strong’ character Style to ‘Synopsis’ than to override the Style format. For example: Code: Sub Demo() Application.ScreenUpdating = False With Selection With .Find .ClearFormatting .Replacement.ClearFormatting .Text = "Synopsis" .Replacement.Text = "^&" .Forward = True .Wrap = wdFindStop .Format = True .MatchCase = True .MatchWholeWord = True .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Replacement.Style = "Body Text" .Execute Replace:=wdReplaceAll .Replacement.Style = "Strong" .Execute Replace:=wdReplaceAll End With End With Application.ScreenUpdating = True End Sub
__________________ |
02-04-2014, 07:29 PM |
|||
|
|||
Is there any way to generate this code using Word’s macro recording mode? When I tried to do a Find «Synopsis» operation, no VBA code was generated. |
02-04-2014, 07:34 PM |
Basic code produced using the macro recorder: Code: Sub Macro1() ' ' Macro1 Macro ' ' Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting Selection.Find.Replacement.Style = ActiveDocument.Styles("Body Text") With Selection.Find .Text = "Synopsis" .Replacement.Text = "^&" .Forward = True .Wrap = wdFindContinue .Format = True .MatchCase = True .MatchWholeWord = True .MatchByte = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll End Sub
__________________ |
02-04-2014, 07:47 PM |
|||
|
|||
How did you get it to record a Find text string operation? |
02-04-2014, 07:50 PM |
By inputting the parameters you see recorded into the Find/Replace dialogue…
__________________ |
02-04-2014, 08:04 PM |
|||
|
|||
It’s recording ok now. I had to use keyboard commands to select the Find operation instead of the mouse. Thanks for all your help! |