循环通过Word文档格式化文本

时间:2013-10-28 17:38:43

标签: vba for-loop ms-word ms-office word-vba

我有一个巨大的文档,其中应该更改以特定单词文本样式开头的行。我为所有这些单词创建了一个数组,并尝试使用For循环格式化文档。但是只有数组中第一个单词的样式才会被更改,而不是数组中的所有单词。

以下是我所做的,请看一下并提出解决方案:

Sub Variables_NormalTxt()
    Dim oRng As Word.Range
    Dim oRngFC As Word.Range
    Dim varUbyteNormal As Variant
    Dim ArrayItem As String
    Dim i As Integer
    varUbyteNormal = Array("uword", "ubyte", "bool", "sword", "const", "ulong", "static")
    Set oRng = ActiveDocument.Range
    i = 0
    For i = 0 To UBound(varUbyteNormal)
    With oRng.Find
        .Text = varUbyteNormal(i)
        .Font.Name = "Times New Roman"
        .Font.Bold = False
        .Font.size = 10
        While .Execute
          oRng.Select
          Set oRngFC = ActiveDocument.Bookmarks("\Line").Range
              oRngFC.Style = "variable normal"
            Wend
        End With
    Next i
End Sub

2 个答案:

答案 0 :(得分:3)

移动此行

Set oRng = ActiveDocument.Range

进入For循环

即。

For i = 0 To UBound(varUbyteNormal)
  Set oRng = ActiveDocument.Range
  With oRng.Find

顺便说一句......

您可以删除该行

i = 0

您的For语句可以推广到

For i = LBound(varUbyteNormal) To UBound(varUbyteNormal)

也许其他人会提出其他改进建议。

(......进一步了解以下内容,但这取决于precisley 你在寻找什么)

Sub Variables_NormalTxt3()
Dim oRng As Word.Range
Dim varUbyteNormal As Variant
Dim ArrayItem As String
Dim i As Integer
varUbyteNormal = Array("uword", "ubyte", "bool", "sword", "const", "ulong", "static")
For i = LBound(varUbyteNormal) To UBound(varUbyteNormal)
  Set oRng = ActiveDocument.Range
  With oRng.Find
    .ClearAllFuzzyOptions
    .ClearFormatting
    .Text = varUbyteNormal(i)
    .Font.Name = "Times New Roman"
    .Font.Bold = False
    .Font.Size = 10
    ' perhaps also...
    .MatchCase = False
    While .Execute
      oRng.Style = "variable normal"
    Wend
  End With
  Set oRng = Nothing
Next 'i
End Sub

答案 1 :(得分:0)

Dim varUbyteNormal As Variant
varUbyteNormal = Array("uword", "ubyte", "bool", "sword", "const", "ulong", "static")

Dim i As Long
For i = LBound(varUbyteNormal) To UBound(varUbyteNormal)

  With ActiveDocument.Range.Find
    .ClearFormatting
    .ClearAllFuzzyOptions

    With .Font
      .Name = "Times New Roman"
      .Bold = False
      .Size = 10
    End With

    .Text = varUbyteNormal(i)

    With .Replacement
      .ClearFormatting
      .Style = "variable normal"
    End With

    .Execute Replace:=wdReplaceAll
  End With

Next