由于Set语句,VBA WORD代码中出现无限循环



我用VBA为MS WORD写了一个简单的代码,其中我想在每个没有点的段落末尾添加点

代码如下:

Function FindParagraph(ByVal doc As Document, ByVal Npara As String) As Paragraph
Dim para As Paragraph

For Each para In doc.Paragraphs
If para.Range.ListFormat.ListString = Npara Then
Set FindParagraph = para
End If
Next para
End Function
Sub End_para_with_dot()
Dim doc As Document
Dim tb As table
Dim prange As Range
Dim srange As Range
Dim para As Paragraph
Dim spara As Paragraph
Dim epara As Paragraph
Dim txt As String

Set doc = ActiveDocument

Set spara = FindParagraph(doc, "1") 
Set epara = FindParagraph(doc, "2")
Set srange = doc.Range(spara.Range.Start, epara.Range.Start) 'sets a specific range of paragraphs in doc

For Each para In srange.Paragraphs
Set prange = para.Range
With prange
If .Style <> "Nagłówek 1" Then
Debug.Print .Text
txt = Trim(.Text)
n = Len(txt)
last_c = Mid(txt, n - 1, 1)
If last_c <> "." Then
txt = Left(txt, n - 1) & "." & Chr(13)
Debug.Print txt
End If
.Text = txt '!!!SUPPOSED REASON FOR ERROR!!!
End If
End With
Next para
End Sub

不幸的是,在我运行这段代码后,会产生一个无限循环,第一个找到的段落一直在打印。

我想是由于.Text = txt线路。早些时候,我在Set prange = para.Range语句中引用了range对象。但我不明白为什么当我想重新分配这个对象的.Text属性时,就会产生无限循环。

如果能给我小费,我将不胜感激。

我假设您不想添加。当段落以!.、:;中的任何一个结尾时;?

尝试通配符查找/替换,其中:

Find = ([!!.,:;?])(^13)
Replace = 1.2

或者,作为一个宏:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([!!.,:;?])(^13)"
.Replacement.Text = "1.2"
.Format = False
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
End With
Application.ScreenUpdating = True
End Sub

最新更新