【问题标题】:Looping through Word document to format text循环遍历 Word 文档以格式化文本
【发布时间】:2013-11-07 14:49:27
【问题描述】:

我有一个巨大的文档,其中以某些特定单词文本样式开头的行应该被更改。我为所有这些单词创建了一个数组,并尝试使用 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

【问题讨论】:

  • 你从不使用搜索结果,只是一些不相关的局部变量。即使是第一个单词,我也看不出样式会如何变化。
  • @GSerg:在 oRng.Select 之后,内置书签“\Line”将指向感兴趣的区域。这很笨拙,但我现在没有时间对那部分进行测试修复 - 也许你有?

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


【解决方案1】:

移动这条线

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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2011-06-19
      相关资源
      最近更新 更多