在 Word VBA 開發中,常需根據文字顏色執行邏輯(如找出藍色標註文字、刪除藍色批註等)。本文提供兩種核心代碼範例:逐字元檢查法與尋找取代法。
ColorIndex適用於需逐字處理、需取得字元位置或內容的情境。
Sub CheckBlueCharByChar()
On Error GoTo ErrHandle
Dim myRange As Range, iChar As Range
Set myRange = ActiveDocument.Range(Selection.Start, ActiveDocument.Content.End)
For Each iChar In myRange.Characters
' ColorIndex = 2 代表 wdBlue (藍色)
If iChar.Font.ColorIndex = wdBlue Then
MsgBox "發現藍色文字: " & iChar.Text & " (位置: " & iChar.Start & ")"
End If
Next
Exit Sub
ErrHandle:
MsgBox "錯誤: " & Err.Number & " - " & Err.Description
End Sub
效能較佳,適合大量文件、需批次刪除、提取或統計藍色文字。
Sub FindBlueText()
Dim n As Long, Info As String
With Selection.Find
.ClearFormatting
.Font.Color = wdColorBlue ' 或 rgbBlue
.Forward = True
.Wrap = wdFindStop
Do While .Execute
n = n + 1
Info = Info & n & vbTab & .Parent.Text & vbCrLf
' .Parent.Delete ' 如需刪除藍色文字,取消註解此行
Loop
End With
If Info = "" Then
MsgBox "未找到藍色字體文字"
Else
Documents.Add.Content.Text = Info ' 在新文件列出結果
End If
End Sub
| 常數 | 值 | 說明 |
|---|---|---|
wdBlue / wdColorBlue | 2 / 8421631 | 標準藍色 |
rgbBlue | 16711680 | RGB(0,0,255) 純藍 |