VBA代码替换Word表格文本后自动添加段落标记问题排查
问题描述
我有一个约10页长的简单Word文档,其中包含一个三列的表格。我需要选中第一列的所有行,移除空格并在开头添加星号,例如“JOHN DOE”变为“*JOHNDOE”。我使用了如下VBA代码:
Dim tbl As Table Dim row As row Dim cell As cell Dim text As String Dim newText As String Dim undoRecord As undoRecord Set tbl = ActiveDocument.Tables(1) ' Change 1 to the index of the table you want to modify Set undoRecord = Application.undoRecord undoRecord.StartCustomRecord "Correct Names" For Each row In tbl.Rows Set cell = row.Cells(1) text = cell.Range.text newText = "*" & Replace(text, " ", "") cell.Range.text = newText ' Overwrite the existing text with the new text Next row undoRecord.EndCustomRecord
代码执行后功能正常,但每个单元格末尾都出现了段落标记(PM),例如“JOHN DOE”变为“*JOHNDOE[PM]”。请问该问题的成因可能是什么?
问题成因分析
- Word表格单元格的
Range.Text属性会包含单元格末尾的特殊隐藏标记:每个单元格默认在内容末尾自带Chr(13)(段落标记)和Chr(7)(单元格结束符),你的代码直接读取cell.Range.Text时,把这两个标记也一起读进来了。 - 你的代码只替换了文本中的空格,但这两个特殊标记里的段落符号没被处理,最后将
newText赋值回单元格时,就把这个段落标记保留了下来,导致显示出[PM]。
内容的提问来源于stack exchange,提问作者O Tal Antiquado
相关产品推荐
相关产品推荐

