使用vba单词更改段落中的文本

时间:2012-08-16 23:39:18

标签: vba ms-word word-vba

我正在尝试使用vba字段更改段落中的文本。以下代码导致Next不会转到集合中的下一个元素。

 Sub ReadPara()
 Dim myString$
 Dim DocPara As Paragraph

 For Each DocPara In ActiveDocument.Paragraphs
   'Debug.Print DocPara.Range.ParagraphStyle '; " - "; DocPara.Range.Text
   If Left(DocPara.Range.ParagraphStyle, Len("Heading")) = "Heading" Then
     Debug.Print DocPara.Range.ListFormat.ListString
   End If
  'This section does not go to the next element in the collection
  If InStr(DocPara.Range.Text, "HW") > 1 Then
    Debug.Print DocPar; qa.Range.Text
    myString$ = DocPara.Range.Text
    DocPara.Range.Text = myString$ & "Changed"
   '  Debug.Print DocPara.Range.Text
  End If
 Next DocPara
 End Sub

5 个答案:

答案 0 :(得分:3)

第二个问题:

ParagraphStyle是只读的,请改用Style。两者都是Variant类型,因此您不使用Set

试试这个:

DocPara.Range.Style = ActiveDocument.Styles("Normal")

答案 1 :(得分:2)

我已经克服了我的第一个问题而且不是错字。错字只是在消息中,而不是在我的代码中。现在我似乎无法改变新修改的段落的样式。

    Option Explicit
    Sub ReadPara()
     Dim myString$
     Dim myHeading$
     Dim DocPara As Paragraph

     For Each DocPara In ActiveDocument.Paragraphs
       If Left(DocPara.Range.ParagraphStyle, Len("Heading")) = "Heading" Then
         myHeading$ = DocPara.Range.ListFormat.ListString
       ElseIf InStr(DocPara.Range.Text, "HW") > 1 Then
         myString$ = DocPara.Range.Text
         myString$ = Replace(myString, "HW", "HW-" & myHeading$)
         DocPara.Range.Text = myString$
         'The line below doesn't work at all
         Set DocPara.Range.ParagraphStyle = ActiveDocument.Styles("Normal")
       End If
     Next DocPara
     End Sub

答案 2 :(得分:2)

现在代码工作了,但我仍然没有进入下一段。我似乎留在同一段。下一个DocPara没有像我期望的那样工作。

    Option Explicit
    Sub ReadPara()

    Dim myString$
    Dim myHeading$
    Dim DocPara As Paragraph
    For Each DocPara In ActiveDocument.Paragraphs
       If Left(DocPara.Range.ParagraphStyle, Len("Heading")) = "Heading" Then
          myHeading$ = DocPara.Range.ListFormat.ListString
       ElseIf InStr(DocPara.Range.Text, "HW") > 1 Then
          myString$ = DocPara.Range.Text
          With DocPara.Range
             myString$ = Replace(myString, "HW", "HW-" & myHeading$)
             .Text = myString$
             .Style = ActiveDocument.Styles("Normal")
          End With
       End If
    Next DocPara
    End Sub

答案 3 :(得分:1)

以下行会导致错误并且(取决于您的错误处理)可能导致执行突然出现循环:

Debug.Print DocPar; qa.Range.Text

如果在每个代码模块的顶部输入Option Explicit(为了强制显式声明每个变量),可能会在之前找到此类错误。 :)

答案 4 :(得分:0)

而不是使用

 For Each DocPara In ActiveDocument.Paragraphs
   'Rest of your code it here
 Next DocPara

使用

 For p = 1 to ActiveDocument.Paragraphs.Count
   'Rest of your code it here
    'use the script below when refering the the specific paragraph
    ActiveDocument.Paragraphs(p). 
 Next p