【问题标题】:How to change text in table for specific adjoining column?如何更改特定相邻列的表格中的文本?
【发布时间】:2021-04-11 23:36:06
【问题描述】:

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

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

之前:

Header 1 [Text
Test: [Text

之后:

Header 1 [Text
Test: Text

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

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

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

    【讨论】:

    • 嗨@macropod,首先,谢谢它看起来很棒。我想我不够清楚(我的错误)。我有几张桌子,每张桌子都有未知数量的行。在每个表中,只有 2 列,第一列用于标题,第二列用于数据。我想在第一列(标题)中找到具有确切标题名称“Test”的行,并在右侧的单元格中将“[”字符替换为“”。
    • 在 Word 中,“标题”一词仅适用于表格顶部的一个或多个整行。请参阅修改后的代码。我也相应地修改了你的问题。
    • 我遇到编译错误:“找不到方法或数据成员”
    • “运行时错误 4218:类型不匹配”指向行:If.InRange(Rng) Then
    • 好的,代码工作了 - 谢谢!但不是只删除文本开头的“[”字符,而是删除所有文本。我应该改变什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多