如何更改 table 中特定相邻列的文本?

How to change text in table for specific adjoining column?

我正在为 WORD 使用 VBA 宏,以便将所有“[”字符替换为“”。 宏工作正常,用于用某种颜色替换所有 table 中的所有字符。

如何添加 if 语句使其仅在列 A 包含“测试”时才起作用

之前:

Header 1 [Text
Test: [Text

之后:

Header 1 [Text
Test: Text

到目前为止我得到了这个并且它工作正常(但是对于所有 table 行而不是特定于“测试”行。

Sub FindChar2()

Dim oTbl As Table
Dim stT As Long, enT As Long
Dim stS As Long, enS As Long

With Selection.Find             ' Replacement
    .Text = "["
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
End With

For Each oTbl In ActiveDocument.Tables

    If oTbl.Shading.BackgroundPatternColor = RGB(176, 255, 137) Then 
    
        oTbl.Columns(1).Select

        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

            Selection.Collapse wdCollapseStart
            Selection.Find.Execute Replace:=wdReplaceOne
            
        Loop
        Selection.Collapse wdCollapseEnd
    
    End If
    
Next
End Sub

假设 'Test' 是 A 列中的唯一内容(我注意到您的样本有“测试:”),您可以使用:

Sub TblFnd()
Application.ScreenUpdating = False
Dim Tbl As Table, Rng As Range
For Each Tbl In ActiveDocument.Tables
  With Tbl
    If .Shading.BackgroundPatternColor = RGB(176, 255, 137) Then
      Set Rng = .Range
      With .Range
        With .Find
          .ClearFormatting
          .Replacement.ClearFormatting
          .Text = "["
          .Forward = True
          .Wrap = wdFindStop
          .Format = False
        End With
        Do While .Find.Execute
          If .InRange(Rng) Then
            If .Cells(1).ColumnIndex = 2 Then
              If Split(.Cells(1).Row.Cells(1).Range.Text, vbCr)(0) = "Test" Then .Text = ""
            End If
          Else
            Exit Do
          End If
          .Collapse wdCollapseEnd
        Loop
      End With
    End If
  End With
Next
Application.ScreenUpdating = True
End Sub