萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

Word 全文批量加拼音巨集:VBA 逐字加注音+空格美化

作者分享 VBA 巨集實現全文自動加拼音:

核心邏輯

  1. 游標移動指令:`Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend` 逐字選取。
  2. 呼叫內建命令:`Application.Run MacroName:="FormatPhoneticGuide"` 彈出拼音指南對話框,再 `SendKeys "{ENTER}", 2` 模擬確定。
  3. 迴圈處理全文每個中文字符(ASCII 碼判斷),完成後再迴圈逐字插入空格,讓拼音不擠在一起,方便兒童拼讀。

完整巨集碼

Sub AddPinYin()
'Author:MissileCat Date:20140410 version:1.0.0
' 為全文逐字加拼音並插入空格
Dim tintTreatingCount As Integer
Dim tstrCharA As String
Dim tlngCurPos As Long
Dim tintA As Integer

Selection.WholeStory
tstrText = Selection.Text
tintTextLength = Selection.Characters.Count
tintlinestart = 1
tintTreatingCount = 0
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1

For tintloopx = 1 To tintTextLength
    tlngCurPos = Selection.MoveRight(Unit:=wdCharacter, Count:=1, Extend:=wdExtend)
    tstrCharA = Right(Selection.Text, 1)
    If AscW(tstrCharA) < 255 And AscW(tstrCharA) > -255 Then
        If tintTreatingCount > 0 Then
            tintA = Len(Selection.Text)
            SendKeys "{ENTER}", 2
            Application.Run MacroName:="FormatPhoneticGuide"
            Selection.MoveRight Unit:=wdCharacter, Count:=tintA
            tintTreatingCount = 0
        End If
    Else
        tintTreatingCount = tintTreatingCount + 1
    End If
Next

' 逐字插入空格
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
For tintloopx = 1 To tintTextLength
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    Selection.TypeText Text:=" "
Next
End Sub

執行前請備份文檔,巨集會修改原文檔結構。

copyright © 萬盛學電腦網 all rights reserved