Consulting

Results 1 to 3 of 3

Thread: Search for text, if found open messagebox

  1. #1
    VBAX Newbie
    Joined
    Jan 2017
    Posts
    2
    Location

    Search for text, if found open messagebox

    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 and appreciate your help very much

    Thomas

  2. #2
    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
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    VBAX Newbie
    Joined
    Jan 2017
    Posts
    2
    Location
    THANK YOU SO MUCH !

    it works perfectly for our purpose



Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •