如何循环宏?

时间:2018-10-24 19:49:05

标签: vba loops fonts ms-word word-vba

为什么此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

enter image description here

1 个答案:

答案 0 :(得分:3)

使用通配符时,请使用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-除非处理可能会用{{ 1}}或出于某些原因,我不想放弃这两个额外的内存字节(sarcasm)。特别是在处理单个单词文档字符(该文档可以包含成千上万个字符)时,您可能会快速溢出Integer。

     

请查看Why Use Integer Instead of Long?,以了解更多信息。