【发布时间】:2020-04-15 20:52:47
【问题描述】:
我正在尝试在 VBA 中编写代码,我将在其中获取具有特定样式的段落的编号(比如说标题 1)。 我正在经历一个循环,不幸的是我收到了这样的错误:
"Object variable or With block variable not set"
这是我的代码:
Public Function FindParagraph(ByVal pStyle As String) As Integer
Dim doc As Document
Dim pNum As Integer
Set doc = ActiveDocument
For pNum = 1 To doc.Paragraphs.Count
Debug.Print pNum, doc.Paragraphs(pNum).Range.Style
If doc.Paragraphs(pNum).Range.Style = pStyle Then
FindParagraph = pNum
Exit For
End If
Next pNum
End Function
Sub DoSth()
Dim i As Integer
i = FindParagraph("Heading 1")
Debug.Print i
End Sub
调试器显示问题出在这一行:
pStyle = doc.Paragraphs(i).Range.Style
实际上,我正在查看我的 Word 文档,它是目录的第一行。
你知道为什么会这样吗?
【问题讨论】:
-
只是关于编辑问题的有用提示。如果您有回复和其他答案,那么您不应该更改原始问题,而是应该添加它(请参阅我的回答),以便您对原始问题的任何 cmet 和回复仍然有意义。
标签: vba ms-word styles paragraph