首页 > 解决方案 > 如何更改特定相邻列的表格中的文本?

问题描述

我正在为 WORD 使用 VBA 宏,以便用“”替换所有“[”字符。该宏可以很好地用某种颜色替换所有表中的所有字符。

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

前:

标题 1 [文本
测试: [文本

后:

标题 1 [文本
测试: 文本

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

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

标签: vbams-word

解决方案


假设“测试”是 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

推荐阅读