由于Set语句,VBA字代码中存在无限循环
我用VBA为MS WORD编写了一个简单的代码, 我想在没有点的段落末尾添加点 代码如下:由于Set语句,VBA字代码中存在无限循环,vba,ms-word,object-reference,Vba,Ms Word,Object Reference,我用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 The
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
函数FindParagraph(ByVal doc作为文档,ByVal Npara作为字符串)作为段落
将段落改为段落
文件段落中的每个段落
如果para.Range.ListFormat.ListString=Npara,则
设置FindParagraph=para
如果结束
下一段
端函数
带点()的子端
将文档变为文档
将tb设置为表格
昏昏欲睡
Dim srange As范围
将段落改为段落
作为段落
将epara作为段落
以字符串形式显示文本
Set doc=ActiveDocument
设置spara=FindParagraph(文件“1”)
设置epara=FindParagraph(文件“2”)
Set srange=doc.Range(spara.Range.Start,epara.Range.Start)”设置文档中段落的特定范围
对于范围段落中的每个段落
设置prange=参数范围
胡闹
如果.Style“Nagłówek 1”,则
调试.打印.文本
txt=修剪(.Text)
n=Len(txt)
last_c=Mid(txt,n-1,1)
如果最后一个字母是“c”,那么
txt=左(txt,n-1)和“.”和“Chr(13)
打印文本
如果结束
.Text=txt'!!!错误的假定原因!!!
如果结束
以
下一段
端接头
不幸的是,在我运行这段代码之后,产生了一个无限循环,第一个找到的段落一直在打印
我想这是由于.Text=txt
行引起的。前面我在语句中引用了range
对象Set prange=para.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
您可以通过Find/Replace非常简单地做到这一点,而不需要宏。或者您可以将查找/替换记录为宏。谢谢@macrood。我在查找行尾的正确签名等方面有问题。例如,我使用^v作为段落字符(通过应用程序插入),但它没有搜索正确的内容。我不知道在哪里可以找到Microsoft列表。我听说这可能是特定的地区。我说得对吗?搜索段落标记的方法是使用^p。段落标记是一种非打印字符,它使单词变成新的段落。^v搜索词在屏幕上查找一个字符,该字符在显示非打印字符时看起来像段落标记