Word find text in table

In this article, we are glad to show you 3 quick ways to find specific text in your Word tables only.

Utilizing the “Find and Replace”, a built-in function in Word, you can search for and find a specific text in a long document. As you see, this is based on the entire document. How about we limit the searching range to Word tables only? Read on to see details.Find Text in Your Word Tables Only

Method 1: Find Text in Selection

  1. First of all, manually select one or more tables in document.
  2. Then click drop-down button next to “Find” command under “Home” tab.
  3. Choose “Advanced Find” to open “Find and Replace” dialog box.
  4. Enter finding text in “Find what” text box.
  5. Click “Find In” tab and choose “Current Selection”.  Enter Text->Click "Find In"->Choose "Current Selection"

Word will find text in your selection only.

Method 2: Find Text in a Table

Besides the usual way, you can choose to run macro to do more customized tasks.

  1. First off, put cursor inside a table where you want to find text.
  2. Then press “Alt+ F11” to open VBA editor.
  3. Click “Normal” on the left column.
  4. Then click “Insert” and choose “Module”.Click "Normal"->Click "Insert"->Click "Module"
  5. Next double click the module to open it.
  6. Paste following codes into module:
Sub FindInATable()
  Dim strText As String
 
  strText = InputBox("Enter finding text here: ")
 
  Application.ScreenUpdating = False
  If Selection.Information(wdWithInTable) = True Then
    With Selection.Tables(1).Range
      With .Find
        .ClearFormatting
        .Text = strText
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute
      End With
      Do While .Find.Found
        .Cells(1).Shading.BackgroundPatternColorIndex = wdBrightGreen
        On Error GoTo handler
        .Collapse wdCollapseEnd
        .Find.Execute
      Loop
    End With
  Else
    MsgBox ("Put cursor inside a table first.")
    Exit Sub
  End If
  handler: Exit Sub
  Application.ScreenUpdating = True
End Sub
  1. Lastly, click “Run”. Enter a text inside the input box and click “OK” to proceed.Paste Codes->Click "Run"Enter Finding Text ->Click "OK"

Method 3: Find Text in All Tables in a Document

  1. First and foremost, repeat steps in method 2 to install and run a macro.
  2. Next replace that macro with this one:
Sub FindTextsInAllTables()
  Dim strText As String
 
  strText = InputBox("Enter finding text here: ")
 
  Application.ScreenUpdating = False
  With Selection
    .HomeKey Unit:=wdStory
    With Selection.Find
      .ClearFormatting
      .Text = strText
      .Forward = True
      .Wrap = wdFindStop
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      .Execute
    End With
    Do While .Find.Found = True
      If .Information(wdWithInTable) = True Then
        .Cells(1).Shading.BackgroundPatternColorIndex = wdBrightGreen
      End If
      .Collapse wdCollapseEnd
      .Find.Execute
    Loop
  End With
  Application.ScreenUpdating = True
End Sub
  1. Similarly, type searching text inside the input box. And click “OK” to proceed.

Rescue Your Data in Time

Once you get compromised data, keep in mind that they are recoverable. So never give up before trying. Under such circumstances, you need to check your latest backup, if any. There is a good chance to have some of your data back. Besides, you can always resort to doc fix tool to recover data.

Author Introduction:

Vera Chen is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including damaged xls and pdf repair software products. For more information visit www.datanumen.com

12 / 11 / 3

Регистрация: 07.09.2015

Сообщений: 256

21.04.2020, 13:45

7

Narimanych,

Цитата
Сообщение от Narimanych
Посмотреть сообщение

Кикие следующие действия после нахождения?

Да там, задача простая. В определённой таблице (именно в таблице №7) найти текст в строке, (например: «Отчёт №3», а их например всего пять),

и удалить все строки

(со столбцами)

идущие до этого текста

(в таблице).
Т.е. скажем так: укоротить таблицу, обрезая её с начала. А флагом остановки, служит искомый текст. Это, то я реализую. Хотя если будет, хороший пример (как выше), буду благодарен.

Цитата
Сообщение от Narimanych
Посмотреть сообщение

Visual Basic
1
2
3
4
5
6
7
Sub MMM()
For i = 1 To Word.ActiveDocument.Tables.Count
   For Each C In ActiveDocument.Tables(i).Range.Cells
   If C.Range.Text Like "*AA*" Then MsgBox ("Table #:" & i & Chr(13) & "Row:" & C.RowIndex & Chr(13) & "Column:" & C.ColumnIndex)
   Next
Next
End Sub

Блин, спасибо! Красивая реализация!
Вот совсем запамятовал про Метод «Like»
И с

Visual Basic
1
For Each C In ActiveDocument.Tables(i).Range.Cells

тоже круто Нуб я в Word…

Не по теме:

Думаю: Т.к. мне искать только в одной таблице, всё ок.
А вот если перебирать каждую ячейку, например в 10 таблицах, то конечно, возможно, метод «Like» не так быстро справится как метод «Find». (не стану писать, что подвиснет, но … есть немного похожий код с выравниванием, вот там тоже все ячейки перебираются, ворд, как-то с этим грустно, справляется).

Добавлено через 24 минуты
Narimanych,

Цитата
Сообщение от Narimanych
Посмотреть сообщение

Кикие следующие действия после нахождения?

На самом деле, ещё один нюанс. Надо будет, потом, после строки (заголовка — «Отчёт №6», она без столбцов) найти максимальное число в последних 4 столбцах (всего столбцов 8).
Хотя опять же, уверен с этим справлюсь.

Не по теме:

Цитата
Сообщение от Schumacher57
Посмотреть сообщение

А вот если перебирать каждую ячейку, например в 10 таблицах, то конечно, возможно, метод «Like» не так быстро справится как метод «Find»

Зря. Всё чётко, и быстро отработал. Проверил, сейчас.



0



  • Remove From My Forums
  • Question

  • Hellow,

    What I want to do: I need to find the text Orange, Grapes & Guava in column 2 and update the text in corresponding cell in column 3 for the same row as “Like”.  

    Col 2

    Col 3

    Apple

    Like

    Orange

    Dislike

    Grapes

    Dislike

    Blue Berry

    Dislike

    Black Berry

    Like

    Guava

    Dislike

    Mange

    Dislike

    regards

    SCOMDev


    SCOMDev

Answers

  • Cross-posted at:
    http://answers.microsoft.com/en-us/office/forum/office_2010-word/how-to-find-and-replace-text-inside-a-table-cells/138626ca-b101-4e0e-9715-55971eb12822

    and
    https://social.msdn.microsoft.com/Forums/office/en-US/7e10b4f7-c611-4f3f-9c1c-4f83aac563e7/extracting-tables-and-images-from-word-document?forum=worddev

    For cross-posting etiquette, please read:
    http://www.excelguru.ca/content.php?184

    Try:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim StrFnd As String, i As Long, Rng As Range
    StrFnd = «Apple,Black Berry»
    With ActiveDocument.Tables(1)
      Set Rng = .Range
      For i = 0 To UBound(Split(StrFnd, «,»))
        With .Range
          With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = Split(StrFnd, «,»)(i)
            .Replacement.Text = «»
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchWildcards = True
            .Execute
          End With
          Do While .Find.Found
            If .InRange(Rng) Then
              If .Cells(1).ColumnIndex = 2 Then
                .Cells(1).Next.Range.Text = «Like»
              End If
            Else
              Exit Do
            End If
            .Collapse wdCollapseEnd
            .Find.Execute
          Loop
        End With
      Next
    End With
    Application.ScreenUpdating = True
    End Sub

    Note: as coded, the macro assumes you want to process the first table in the document. If you want to work with a different table, change the (1) in ‘ActiveDocument.Tables(1)’ to refer to that table. If you want to work with a selected table,
    change ‘ActiveDocument’ to ‘Selection’.


    Cheers
    Paul Edstein
    [MS MVP — Word]

    • Edited by

      Monday, October 27, 2014 9:32 PM
      Updated code

    • Proposed as answer by
      Fei XueMicrosoft employee
      Tuesday, October 28, 2014 6:08 AM
    • Marked as answer by
      Fei XueMicrosoft employee
      Wednesday, November 5, 2014 12:22 PM

Hello — I have a tool to find and replace text within Word documents in a specified folder that I’ve cobbled together, which works pretty well. However, I need to be able to find text within a table in the specified document(s) and then replace text that is three cells to the right of that found text. Alternately, I need to be able to find specific text in the table, then find other specific text in the same row and replace that. Hope that makes sense. Table would look something like this:


Dog | Food | Dish | Water

Cat | Food | Bowl | Milk

Bird | Seed | Bottle | Water


I would want to find the row with «Bird» and then replace «Water» with «Juice». I don’t want to replace the first instance of «Water» (in the «Dog» row); only in the row starting with «Bird.»

Any ideas? My code is below:


Sub FindReplace()

Dim rngStory As Word.Range

Dim pFindTxt As String

Dim pReplaceTxt As String

Dim lngJunk As Long

Dim oShp As Shape

pFindTxt = InputBox(«Enter the text that you want to find.» _

, «FIND»)

If pFindTxt = «» Then

MsgBox «Cancelled by User»

Exit Sub

End If

TryAgain:p

ReplaceTxt = InputBox(«Enter the replacement.», «REPLACE»)

If pReplaceTxt = «» Then

If MsgBox(«Do you just want to delete the found text?», _

vbYesNoCancel) = vbNo Then

GoTo TryAgain

ElseIf vbCancel Then

MsgBox «Cancelled by User.»

Exit Sub

End If

End If

Dim FolderName As String

With Application.FileDialog(msoFileDialogFolderPicker)

.AllowMultiSelect = False

.Show

On Error Resume Next

FolderName = .SelectedItems(1)

Err.Clear

On Error GoTo 0

End With

Dim fso, newFile, folder, files

Set fso = CreateObject(«Scripting.FileSystemObject»)

Set folder = fso.GetFolder(FolderName)

Set files = folder.files

For Each file In files

Documents.Open FileName:=file.Path

Application.DisplayAlerts = False

‘Fix the skipped blank Header/Footer problem

lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType

‘Iterate through all story types in the current document

For Each rngStory In ActiveDocument.StoryRanges

‘Iterate through all linked stories

Do

SearchAndReplaceInStory rngStory, pFindTxt, pReplaceTxt

On Error Resume Next

Select Case rngStory.StoryType

Case 6, 7, 8, 9, 10, 11

If rngStory.ShapeRange.Count > 0 Then

For Each oShp In rngStory.ShapeRange

If oShp.TextFrame.HasText Then

SearchAndReplaceInStory oShp.TextFrame.TextRange, _

pFindTxt, pReplaceTxt

End If

Next

End If

Case Else

‘Do Nothing

End Select

On Error GoTo 0

‘Get next linked story (if any)

Set rngStory = rngStory.NextStoryRange

Loop Until rngStory Is Nothing

Next

ActiveDocument.Save ActiveDocument.Close

Next

Application.DisplayAlerts = True

MsgBox «Done!»

End Sub


Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, _

ByVal strSearch As String, ByVal strReplace As String)

With rngStory.Find

.ClearFormatting

.Replacement.ClearFormatting

.Text = strSearch

.Replacement.Text = strReplace

.Wrap = wdFindStop ‘Continue

.Execute Replace:=wdReplaceOne ‘All

End With

End Sub

Written by Allen Wyatt (last updated July 18, 2022)
This tip applies to Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365


When Peter wants to find a word at the end of a paragraph, he searches for XXX^p and replaces it with YYY^p. This doesn’t, however, find words at the very end of table cells. He wonders how he can search and replace the words at the end of table cells and if there is a special code similar to ^p.

There is no special code similar to ^p (end of paragraph) to indicate the end of a cell. There is a trick you can try, however, that works well for many people.

First, create a unique paragraph style that you will use only for the contents of the cells in your table. Make sure you apply this style to all of the cells within the table. Next, use Find and Replace to search for the style. In the Replace With box, enter the code ^& followed by what you want to add to the end of the cell. Then, step through all occurrences and do your replacements, as desired. The ^& code specifies that you want to replace what you found (the text in the cells formatted with the unique style) with what you actually found.

If you want to replace a specific word in the table cells (XXX) with something new (YYY), you can follow the same steps as above, simply search for any occurrences of XXX using the unique table-cell style and replace it with YYY. You’ll still want to step through the matches and determine if the replacement should be made on a case-by-case basis, but you will be able to make the changes in your table much quicker.

WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (13571) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Shortcut for AutoCorrect Dialog Box

There is no built-in keyboard shortcut that will display the AutoCorrect dialog box. This doesn’t mean that there aren’t …

Discover More

Grabbing the MRU List

Want to use the list of most recently used files in a macro? You can access it easily by using the technique presented in …

Discover More

Creating a Log/Log Chart

If you need to create a chart that uses logarithmic values on both axes, it can be confusing how to get what you want. …

Discover More

More WordTips (ribbon)

Nudging a Table

When laying out a page, you often need to move objects around to get them into just the right position. Word allows you …

Discover More

Formatting an ASCII Table with Tabs

If you get a document from a coworker that has tabs used to line up tabular information, you might want to change that …

Discover More

Table Rows Truncated in Printout

If you have problems getting the printout of a table to look correct, it can be frustrating. This tip provides a few …

Discover More

Like this post? Please share to your friends:
  • Word find some letters
  • Word find search online
  • Word find search and look for
  • Word find puzzles for christmas
  • Word find puzzle page