首页 > 解决方案 > 如何循环宏?

问题描述

为什么这个 VBA 代码不起作用?这些文档使用了一种特殊的字体,称为rage, wait, arial。我想遍历文档的每个字母,并且每当.Font = "*rage*"我想遍历十几个字母时。(我的中风 - 耐心。)

 Sub grandma()

 Dim doc As Document
 Set doc = ActiveDocument
 Dim Counter As Integer

 For i = 1 To 6
      doc.Range.Characters.Count
      If doc.Range.Characters(i).Font.Name = "*rage*" Then
         doc.Range.Characters(i).Font.Name = "Waiting for the Sunrise"
      End If
      If doc.Range.Characters(i).Font.Name = "*wait*" Then
         doc.Range.Characters(i).Font.Name = "Rage Italic"
      End If
      If doc.Range.Characters(i).Font.Name = "*arial*" Then
         doc.Range.Characters(i).Font.Name = "Arial Nova Cond Light"
      End If
      j = i

 MsgBox "Hi! " & i
 Next i

 End Sub

在此处输入图像描述

标签: vbaloopsfontsms-word

解决方案


使用Like运算符而不是=使用通配符时。

 Option Explicit

 Sub grandma()

     Dim doc As Document
     Set doc = ActiveDocument
     Dim i As Integer

     For i = 1 To 6

        With doc.Range.Characters(i).Font
            Select Case True
            Case .Name like "*rage*"
                .Name = "Waiting for the Sunrise"
            Case .Name Like "*wait*"
                .Name = "Rage Italic"
            Case .Name Like "*arial*"
                .Name = "Arial Nova Cond Light"
            End Select
        End With

        MsgBox "Hi! " & i

     Next i

 End Sub

旁注:我个人的偏好是避免使用数据类型Integer,而是使用Long- 除非处理会溢出的遗留应用程序 aLong或出于某种原因我不想放弃这两个额外的内存字节(讽刺)。尤其是在处理单个 word 文档字符时- 一个文档可能包含数千个字符,您可以快速溢出 Integer。

看看为什么使用整数而不是长整数?了解更多信息。


推荐阅读