【问题标题】:VBA replacing all matches in the table (Word)VBA 替换表中的所有匹配项(Word)
【发布时间】:2021-09-29 17:55:17
【问题描述】:

我在 Word 中有一个表格,在第三行我有“1. Text”,我正在尝试删除点。我知道不用vba也可以,我只是在练习一些简单的东西。

Sub Test()

Dim replacePattern As String
Dim RE As RegExp
Set RE = New RegExp

RE.Pattern = "(^[0-9]).(\s[A-Za-z\s]*)"
RE.Global = True
replacePattern = "$1$2"

Set Matches = RE.Execute(Selection.Text)
For Each Match In Matches
    Selection.Text = RE.Replace(Selection.Text, replacePattern)
Next
End Sub

现在它只替换第一个选定单元格中的文本。我怎样才能正确地做到这一点?

【问题讨论】:

  • 尝试添加RE.Multiline = True。另外,转义.RE.Pattern = "^([0-9])\.(\s[A-Za-z\s]*)"

标签: regex vba ms-word


【解决方案1】:

这里的棘手部分是处理表格单元格中的文本。 你现在这样做的方式会删除很多表格信息,你最终会得到一个乱码。
如果你逐个单元格地做,它会更容易:

For Each Table In ActiveDocument.Tables
    For Each Cell In Table.Range.Cells
        Set Matches = RE.Execute(Cell.Range.Text)
        For Each Match In Matches
            Cell.Range.Text = RE.Replace(Cell.Range.Text, replacePattern)
        Next
    Next
Next

【讨论】:

  • 这应该使用通配符单词搜索来完成。通过 selection.Tables(1).range 可以很容易地获得 Table 范围,假设当前选择点在 Table 中。
猜你喜欢
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
相关资源
最近更新 更多