搜索并替换vba中的所有特殊字符

时间:2016-02-02 07:56:10

标签: vba ms-word

我是vba的新手,我的目标是将特殊字符替换为COMMA e.t.c.我如何编写代码,如果我按照下面的代码我的代码变得非常长。这是替代方法吗?

Dim comma As Range
For Each comma In ActiveDocument.StoryRanges
    With comma.Find
      .Text = ","
      .Replacement.Text = "#@KE_COMMA@#"
      .Wrap = wdFindContinue
      .Execute Replace:=wdReplaceAll
    End With
  Next comma

3 个答案:

答案 0 :(得分:1)

使用此代码

Sub shalu()
s = sss(",", "Repace_Comma")
s = sss(".", "Replace_dot")
s = sss("-", "replace_hyphen")
End Sub

Public Function sss(A As String, B As String) As String

Dim myword As Range

 For Each myword In ActiveDocument.StoryRanges
    With myword.Find
      .Text = A
      .Replacement.Text = B
      .Wrap = wdFindContinue
      .Execute replace:=wdReplaceAll
    End With
  Next myword
End Function

答案 1 :(得分:0)

这是我使用的,当我想在Excel中替换某些内容时。你可以稍微改一下,所以它也适用于Word。

Public Sub remove_space_in_string()

Dim r_range As Range

For Each r_range In Selection
    r_range = Trim(r_range)
    r_range = Replace(r_range, vbTab, "")
    r_range = Replace(r_range, " ", "")
    r_range = Replace(r_range, Chr(160), "")
Next r_range

End Sub

答案 2 :(得分:0)

我的建议是将所有特殊字符和replacemnt值存储在数组中,并像你一样迭代所有范围。

Dim comma As Range
For i=0 to Ubound(arraySpCahr)-1
For Each comma In ActiveDocument.StoryRanges
With comma.Find
  .Text = arraySpCahr(i) ' arraySpCahr(0)="," (1)="-"...etc
  .Replacement.Text = "#@KE_COMMA@#"
  .Wrap = wdFindContinue
  .Execute Replace:=wdReplaceAll
End With
Next comma
Next i
相关问题