vba - 找到所有标题 1 的文本并将其放入一个数组中

标签 vba ms-word

我正在使用 VBA 宏来呈现 Word 文档中的所有“标题 1”样式文本。
它工作正常,但花费大量时间取决于 word doc 的内容。

我正在循环每个段落以检查“标题 1”样式并将文本呈现为数组。

我想知道是否有另一种方法可以简单地找到“标题 1”样式并将文本存储在数组中,这将大大减少执行时间。

在我的宏程序下方,我将不胜感激任何关于上述问题的专家意见。

Sub ImportWordHeadings()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim sHeader(50) As String
Dim Head1counter As Integer
Dim arrcount As Long
Dim mHeading As String

On Error Resume Next
wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
"Browse for file containing table to be imported")

If wdFileName = False Then Exit Sub '(user cancelled import file browser)

Set wdDoc = GetObject(wdFileName) 'open Word file


 p = 1
  RetCount = 0
  parg = wdDoc.Paragraphs.Count

For Head1counter = 1 To parg

   If wdDoc.Paragraphs(Head1counter).Range.Style = "Heading 1" Then

        sHeader(p) = wdDoc.Paragraphs(Head1counter).Range.Text
        p = p + 1
        Else
        p = p
   End If
Next Head1counter

For arrcount = RetCount + 1 To UBound(sHeader)

  If sHeader(arrcount) <> "" Then
        Debug.Print sHeader(arrcount)
        RetCount = arrcount
Exit For
  Else
        RetCount = RetCount
  End If
Next arrcount

Set wdDoc = Nothing

End Sub

最佳答案

您可以使用 Find method搜索所有标题,与我所做的非常相似 over here on Code Review .

Set doc = ActiveDocument
Set currentRange = doc.Range 'start with the whole doc as the current range

With currentRange.Find
    .Forward = True             'move forward only
    .Style = wdStyleHeading1    'the type of style to find
    .Execute                    'update currentRange to the first found instance

    dim p as long 
    p = 0
    Do While .Found

        sHeader(p) = currentRange.Text

        ' update currentRange to next found instance
        .Execute
        p = p + 1
    Loop
End With

关于vba - 找到所有标题 1 的文本并将其放入一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842501/

相关文章:

vba - 如何使用 Word 宏从已打开的 Excel 工作簿中获取数据?

ms-word - 如何比较两个word文档?

excel - 如何循环遍历列给定的次数

excel - 使用 JIRA 图表动态创建 MS Word 报告?

vba - VBA阵列-检查严格(非近似)匹配

excel - 仅当 Windows 任务计划程序打开文件时才运行 Excel VBA

c# - 如何使用 office interop API 枚举 word 文档?

c# - 如何在 C# 中从模板创建 *.docx 文件

vba - 在 VBA 中向上舍入到最接近的较大整数

Excel 崩溃,VBA 用户窗体无法保存