PDA

View Full Version : [SOLVED:] Search for text, if found open messagebox



thoerzer
01-20-2017, 03:01 AM
Dear vba coders,

I'm working on a large word2010 document for my company. Because in the document there are a lot of cross references that I want to check before printing them. Due to the fact that other users work with this document as well I want to make sure that all cross references are valid.

I am only thinking of a simple string search and if this string has been found in the document a message box should open

I searched already the internet and tried to program my own code, but it didn't work out sadly...
This code I found in the internet but it doesn't work somehow in Word2010 (I marked them red)

Sub Fehlersuche()

Dim strFind As String = "find me"
With ThisApplication.Selection.Find
.ClearFormatting()
.Text = strFind
If .Execute = True Then
MessageBox.Show ("Text found.")
Else
MessageBox.Show ("The text could not be located.")
End If
End With
End Sub



I'm a VBA noobie :crying: and appreciate your help very much:hi:

Thomas

gmayor
01-20-2017, 04:42 AM
Try the following instead. Note that in order to select each occurrence, it will need to open the header/footer if found there.


Sub FindString()
Dim oStory As Range
Dim strFind As String: strFind = "Lorem"
For Each oStory In ActiveDocument.StoryRanges
With oStory.Find
Do While .Execute(FindText:=strFind)
oStory.Select
MsgBox oStory.Text
oStory.Collapse 0
Loop
End With
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
With oStory.Find
Do While .Execute(FindText:=strFind)
oStory.Select
MsgBox oStory.Text
oStory.Collapse 0
Loop
End With
Wend
End If
Next oStory
Set oStory = Nothing
lbl_Exit:
Exit Sub
End Sub

thoerzer
01-20-2017, 05:12 AM
THANK YOU SO MUCH !

it works perfectly for our purpose


:hi: