使用宏在Word中搜索表以查找单元格中的特定字符串,然后在同一行中的另一个单元格上设置排版 [英] Use macro to search table in Word to find specific string in a cell and then set typography on another cell in the same row
问题描述
我有一个Word文档,其中包含3列的表,行数未知,并且 我需要一个可以在第1列中搜索字符串"Sum"的宏.
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.
如果找到完全匹配的宏,则必须将行中剩余的两个单元格的版式设置为Word中的两个不同的版式,并删除单元格1中的字符串"Sum".
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.
该表可以包含字符串"sum"的许多实例,但是它们始终位于第一列中.
The table can contain many instances of the string "sum" but they wil alwaye be in the first column.
我尝试过的代码,由于我缺乏编码技巧而深表歉意,但是我只在一周内这样做,直到第一个"sum"实例都可以正常工作,然后退出.
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.
我正在使用以下代码:
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
希望你能帮助我.
推荐答案
这似乎可行
忽略表外的总和"
通过两个表进行测试
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
这篇关于使用宏在Word中搜索表以查找单元格中的特定字符串,然后在同一行中的另一个单元格上设置排版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!