我正在尝试在VBA中编写代码,在该代码中,我将获得具有特定样式的段落编号(例如标题1)。我正在经历一个循环,不幸的是我遇到了这样的错误:
"Object variable or With block variable not set"
这是我的代码:
Sub FindParagraph()
Dim doc As Document
Dim pStyle As String
Dim i As Integer
Set doc = ActiveDocument
i = 1
pStyle = doc.Paragraphs(i).Range.Style
While Not pStyle <> "Heading 1"
i = i + 1
pStyle = doc.Paragraphs(i).Range.Style
Debug.Print i, pStyle
Wend
End Sub
调试器显示问题出在这一行:pStyle = doc.Paragraphs(i).Range.Style
实际上,我正在查看我的Word文档,它是目录的第一行。你知道为什么会这样吗?
您提供的代码无法编译。它在
处给出错误While Not (IsEmpty(pStyle))
因为方法IsEmpty仅应用于Variant类型,并且分配给pStyle的类型是String。为了实现您的意图,您需要将此行更改为
While Not pStyle = vbNullString