我需要检查 Microsoft Word 中所选内容的每一行上第一个非空白字符的字体,如果是 Courier New,则对其进行一些处理。我有以下代码,但似乎效率低下。请问有更直接的方法吗?
Dim lineRange As Range
Dim trimmedText As String
Dim i As Long
' Iterate over each paragraph in the selection range
For Each lineRange In selectionRange.Paragraphs
' Trim the paragraph text to remove leading and trailing spaces
trimmedText = Trim(lineRange.Range.Text)
' Find the index of the first non-blank character
i = 1
Do While i <= Len(trimmedText) And Mid(trimmedText, i, 1) = " "
i = i + 1
Loop
' Check if there's at least one non-blank character in the trimmed text
If i <= Len(trimmedText) Then
' Set the range to the first non-blank character
Set lineRange = lineRange.Range.Characters(i)
' Check the font name of the first non-blank character
If lineRange.Font.Name = "Courier New" Then
' Process the Courier New line here
End If
End If
Next lineRange
Do Loop
没有必要。LTrim
去掉前导空格,然后就可以得到第一个非空白字符的位置索引Selection
是一个 Range 对象。 lineRange
应声明为 Paragraph
对象。For Each lineRange In selectionRange.Paragraphs
微软文档:
Option Explicit
Sub Demo()
Dim lineRange As Paragraph, rTarget As Range
Dim trimmedText As String
Dim i As Long
' Iterate over each paragraph in the selection range
For Each lineRange In Selection.Paragraphs
With lineRange.Range
' Trim the paragraph text to remove leading spaces
trimmedText = LTrim(.Text)
If Not trimmedText = vbCr Then ' Skip the blank paragraph
i = Len(.Text) - Len(trimmedText) ' count of leading space
' Set the range to the first non-blank character
Set rTarget = .Characters(i + 1)
' Check the font name of the first non-blank character
If rTarget.Font.Name = "Courier New" Then
' ** Process the Courier New line here
' lineRange.Range.Bold = True
End If
End If
End With
Next lineRange
End Sub