WORD-通过引号中的“文本”查找和替换文本

时间:2019-04-01 12:25:29

标签: vba ms-word

如何在引号文本之间查找和修剪空格?

例如:如果单词包含以下字符串: 我对他说'我为什么要呢?他回答... 它将替换: 我对他说:“为什么?他回答...

我知道在引号中查找文本的正则表达式为:(\'*?\'),但从这里开始我无法继续前进。

任何帮助将不胜感激 阿西

1 个答案:

答案 0 :(得分:0)

对于VBA解决方案,请尝试:

Sub Demo()
Dim Rng As Range, Rslt
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "[‘'][!^13^l^t]@['’]"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    .Select
    Set Rng = .Duplicate
    With Rng
      .Start = .Start + 1
      .End = .End - 1
      If .Text <> Trim(.Text) Then
        Rslt = MsgBox("Trim this instance?", vbYesNoCancel)
        If Rslt = vbCancel Then Exit Sub
        If Rslt = vbYes Then
          Do While .Characters.Last = " "
            .Characters.Last = vbNullString
          Loop
          Do While .Characters.First = " "
            .Characters.First = vbNullString
          Loop
        End If
      End If
    End With
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
End Sub

注意::如果字符串未应用任何格式,则可以减少:

  Do While .Characters.Last = " "
    .Characters.Last = vbNullString
  Loop
  Do While .Characters.First = " "
    .Characters.First = vbNullString
  Loop

收件人:

  .Text = Trim(.Text)

要仅在选定范围内工作,请更改:

Dim Rng As Range, Rslt
With ActiveDocument.Range

收件人:

Dim Rng As Range, RngSel As Range, Rslt
With Selection.Range
  Set RngSel = .Duplicate

并插入:

    If .InRange(RngSel) = False Then Exit Sub

之前:

    .Select