问题
I have a Word document with a table of 3 columns and an unknown number of rows and I need a macro that can search for the string "Sum" in column 1.
If an exact match is found the macro must set the typography of the two remaining cells in the row to two different typographies from Word and also delete the string "Sum" in cell 1.
The table can contain many instances of the string "sum" but they wil alwaye be in the first column.
The code I have tried, and I apologize for my lack of coding skills, but I have only been doing this for at week, works fine until the first instance of "sum" and then just quits.
I am using this code:
Sub FindSum()
Dim oTbl As Table
Dim oRow As Row
Set myRange = ActiveDocument.Content
For Each oTbl In ActiveDocument.Tables
For Each oRow In oTbl.Rows
Selection.Find.Execute FindText:="Sum", ReplaceWith:=""
If Selection.Find.Found = True Then
Selection.MoveRight Unit:=wdCell
Selection.Style = ActiveDocument.Styles("Titel")
Selection.MoveRight Unit:=wdCell
Selection.Style = ActiveDocument.Styles("Citat")
End If
Next
Next
End Sub
I hope you can help me.
回答1:
this appears to work
ignores "Sum" outside of tables
tested with two tables
Option Explicit
Sub FindSum()
Dim oTbl As Table
Dim stT As Long, enT As Long
Dim stS As Long, enS As Long
With Selection.Find ' the settings remain until changed
.Text = "Sum"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
For Each oTbl In ActiveDocument.Tables
oTbl.Columns(1).Select ' not sure if this is required
Do While Selection.Find.Execute
stT = oTbl.Range.Start ' table range
enT = oTbl.Range.End
stS = Selection.Range.Start ' found text range
enS = Selection.Range.End
If stS < stT Or enS > enT Then Exit Do ' text found inside table ???
Selection.Collapse wdCollapseStart
Selection.Find.Execute Replace:=wdReplaceOne
Selection.MoveRight Unit:=wdCell
Selection.Style = wdStyleTitle ' original code was invalid
Selection.MoveRight Unit:=wdCell
Selection.Style = wdStyleHeading3
Loop
Selection.Collapse wdCollapseEnd
Next
End Sub
来源:https://stackoverflow.com/questions/46856136/use-macro-to-search-table-in-word-to-find-specific-string-in-a-cell-and-then-set