增加新段落后更新.Paragraphs.Count变量

时间:2017-07-13 15:38:34

标签: vba word-vba

我有一个代码,我想遍历整个文档,检查它是否以数字开头,如果是,则添加一个段落。

但是,它不会计算循环中的新段落,因此在文档结束之前它不会执行。

Sub test()

lastpar = ActiveDocument.Paragraphs.Count

For i = 1 To lastpar

If IsNumeric(ActiveDocument.Paragraphs(i).Range.Words(1).Characters(1)) = True Then
If ActiveDocument.Paragraphs(i + 1).Range.Characters.Count > 1 Then
ActiveDocument.Paragraphs(i).Range.Paragraphs.Add
lastpar = lastpar + 1
End If
End If

Next i

End Sub

正如您所看到的,我尝试在代码中添加lastpar = lastpar + 1,但它仍然无效。

1 个答案:

答案 0 :(得分:0)

通过添加While i < lastpar

进行管理以使其有效
Sub test()

lastpar = ActiveDocument.Paragraphs.Count

While i < lastpar

For i = 1 To lastpar

If IsNumeric(ActiveDocument.Paragraphs(i).Range.Words(1).Characters(1)) = True Then
If ActiveDocument.Paragraphs(i + 1).Range.Characters.Count > 1 Then
ActiveDocument.Paragraphs(i).Range.Paragraphs.Add
lastpar = lastpar + 1
End If
End If

Next i

Wend

End Sub