修改表格单元格的.Range.Text会删除所有附加的注释

时间:2016-01-21 08:42:00

标签: vba replace ms-word word-vba

我编写了一个小型VBA程序,用于从MS Word表格单元格中删除尾随空格。它遍历每个表的所有单元格,并使用命令

修改其.Range.Text对象
C.Range.Text = myRE.Replace(C.Range.Text, "")

其中myRE是VBScript RegExp 5.5对象和myRE.Pattern = "\s+(?!.*\w)"。可以找到整个程序here

除一个问题外,程序运行正常。它也会删除单元格中的所有注释。之前:

Screenshot before

之后(额外的空间消失了,评论也是如此):

Screenshot after

查看本地对象树,我可以看到更改C.Range.Text也会更改C.Range.Comments - 但为什么?

Object tree before and after

我该怎么做才能防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

当您使用Range.Text时,就像使用RegEx或实际上任何操作字符串的函数一样,当纯字符串写回单元格时,所有格式化和其他非文本字符都将丢失。

例如,如果单元格文本中的单个字符被格式化为粗体,则粗体格式将丢失。或者,如果更改跟踪在单元格中 - 它将丢失。任何脚注或尾注都将丢失。评论属于同一类别。

您需要一种不同的方法,一种尊重Word如何在文档中存储非文本信息的方法。这里建议循环表格中的单元格,在单元格的末尾拾取范围,然后只要找到预定义的空白字符就移回范围的起始点。当不再符合此标准时,将删除范围。 (注意我不知道为什么我需要两次使用Range.Delete - 第一次没有效果。)

你需要找出适合自己的东西"空白"。我使用了空格,回车和制表符。您当然可以将其他内容添加到sWhitespace字符串中。

Sub RemoveWhiteSpaceEndOfCell()
  Dim cel As word.Cell
  Dim sWhitespace As String
  Dim rng As word.Range
  Dim lWhiteSpaceChars As Long

  'define what constitutes Whitespace. 
  'Here: a space, a carriage return and a tab
  sWhitespace = Chr(32) & Chr(13) & Chr(9)
  For Each cel In ActiveDocument.Tables(1).Range.Cells
    Set rng = cel.Range
    'set the Range to the end of the cell
    rng.Collapse wdCollapseEnd
    rng.MoveEnd wdCharacter, -1
    'move the starting point back as long as whitespace is found
    lWhiteSpaceChars = rng.MoveStartWhile(sWhitespace, wdBackward)
    'Only if whitespace was found, delete the range
    If lWhiteSpaceChars <> 0 Then
        'rng.Select 'For debugging purposes
        rng.Delete
        rng.Delete
    End If
  Next
End Sub