首页 > 代码库 > word中利用宏替换标点标点全角与半角

word中利用宏替换标点标点全角与半角

Alt+F11,然后插入-模块:

技术分享

复制下面代码到编辑窗口:

Sub 半角标点符号转换为全角标点符号()中英互译文档中将中文段落中的英文标点符号替换为中文标点符号    Dim i As Paragraph, ChineseInterpunction() As Variant, EnglishInterpunction() As Variant    Dim MyRange As Range, N As Byte    定义一个中文标点的数组对象    ChineseInterpunction = Array("", "", "", "", "", "", "……", "", "", "", "", "", "", "", "", "", "")    定义一个英文标点的数组对象    EnglishInterpunction = Array(".", ",", ";", ":", "?", "!", "", "-", "~", "(", ")", "<", ">", "", "", """", """")    On Error Resume Next    Application.ScreenUpdating = False    关闭屏幕更新    For Each i In ThisDocument.Paragraphs    遍历文档每个段落        If Asc(i.Range) < 0 Then    如果段落首个字符为汉字(汉字字符的ASC<0)            定义一个RANGE对象            For N = 0 To 13    进行14次循环                Set MyRange = i.Range    定义一个RANGE对象                With MyRange.Find    查找                    .ClearFormatting    清除查找格式                    查找相应的英文标点,替换为对应的中文标点                    .Execute findtext:=EnglishInterpunction(N), replacewith:=ChineseInterpunction(N), Replace:=wdReplaceAll                End With            Next        End If    Next    Selection.HomeKey wdStory    With Selection.Find        .ClearFormatting    清除查找格式        .Text = """"    查找"        如果查找成功并且在中文段落中,分别将其替换为“/”        While .Execute            If Asc(Selection.Paragraphs(1).Range) < 0 Then Selection.Text = ""            If .Execute And Asc(Selection.Paragraphs(1).Range) < 0 Then Selection.Text = ""        Wend    End With    Selection.HomeKey wdStory    With Selection.Find        .ClearFormatting    清除查找格式        .Text = ""    查找‘        While .Execute            如果查找成功并且在中文段落中,分别将其替换为‘/’            If Asc(Selection.Paragraphs(1).Range) < 0 Then Selection.Text = ""            If .Execute And Asc(Selection.Paragraphs(1).Range) < 0 Then Selection.Text = ""        Wend    End With    恢复屏幕更新    Application.ScreenUpdating = TrueEnd Sub

然后Alt+F8,选择刚刚添加的宏,并运行:

技术分享

---分割线---

还有另一段代码,简洁一些:

Sub 全角转换为半角()    使用前需先选中要替换的区域    Dim fullshape, halfshape As String, i As Integer 定义fullshape(全角)、halfshape(半角)为字符串型,i为整数型    fullshape = ",。?“”‘’!:;"    halfshape = ",.?""‘‘!:;"    For i = 1 To 10 循环10次    With Selection.Find    .Text = Mid(fullshape, i, 1) mid函数:返回文本字符串中从指定位置开始的特定数目的字符,每次取一个标点符号    .Replacement.Text = Mid(halfshape, i, 1) 将用于替换的相应位置的半角标点符号    .Format = False 保留替换前的字符格式    .Execute Replace:=wdReplaceAll 用半角标点替换全角标点    End With    Next i    End Sub

 

word中利用宏替换标点标点全角与半角