1

我正在尝试使用 vba word 更改段落中的文本。以下代码导致 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
4

5 回答 5

3

第二个问题:

ParagraphStyle是只读的,请Style改用。两者都是 type Variant,所以你不要使用Set.

尝试这个:

DocPara.Range.Style = ActiveDocument.Styles("Normal")
于 2012-08-19T08:20:47.753 回答
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
于 2012-08-22T15:18:03.257 回答
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
于 2012-08-17T15:28:42.987 回答
1

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

Debug.Print DocPar; qa.Range.Text

如果你Option Explicit在每个代码模块的顶部输入(为了强制每个变量都被显式声明),这种错误可能会更早发现。:)

于 2012-08-17T06:32:19.877 回答
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
于 2015-10-30T07:12:42.503 回答