首页 > 解决方案 > 在 Word 文档中查找“标题”样式

问题描述

我有一个 Word 宏,它允许将他/她的光标放在 Word 文档中的任何位置,它会查找并保存用户选择的文本上方的标题 1、标题 2 和标题 3 文本,以便捕获章节、部分和与文档中的任何句子相关联的子部分。

我目前正在使用下面的代码逐行向上移动文档,直到找到包含“标题 x”的样式。完成此任务后,我将向上移动的行数向下移动以到达标题 1,这可能是很多页。

正如您可以想象的那样,这很尴尬,需要很长时间(有时 60 多秒)并且在视觉上令人不安。

下面的代码是标识标题的子程序。

 Dim str_heading_txt, hdgn_STYLE As String 
 Dim SELECTION_PG_NO as  Integer 
     hdng_STYLE = Selection.Style
     Do Until Left(hdng_STYLE, 7) = "Heading"
             LINESUP = LINESUP + 1
             Selection.MoveUp Unit:=wdLine, COUNT:=1
             Selection.HomeKey Unit:=wdLine
             Selection.EndKey Unit:=wdLine, Extend:=wdExtend
             hdng_STYLE = Selection.Style
             'reached first page without finding heading
             SELECTION_PG_NO = Selection.Information(wdActiveEndPageNumber)
             If SELECTION_PG_NO = 1 Then     'exit if on first page
        a_stop = True
                 Exit Sub
             End If
     Loop 
     str_heading_txt = Selection.Sentences(1)

我尝试了下面的另一种方法,以使用下面的 Range.Find 命令消除滚动和性能问题。

我无法让选择范围移动到具有“标题 1”样式的文本。代码在初始选择时选择句子,而不是“标题 1”样式的文本。

理想情况下,查找命令会将我带到包含“标题”的任何样式,但如果需要,我可以分别为“标题 1”、“标题 2”和“标题 3”编码。

需要对代码进行哪些更改才能选择“标题 1”,或者选择“标题”?

Dim str_heading_txt, hdgn_STYLE As String
Dim Rng As Range
Dim Fnd As Boolean

Set Rng = Selection.Range
With Rng.Find
    .ClearFormatting
    .Style = "Heading 1"
    .Forward = False
    .Execute

    Fnd = .Found
End With

If Fnd = True Then
    With Rng
        hdng_STYLE = Selection.Style
        str_heading_txt = Selection.Sentences(1)
    End With
End If

真诚感谢任何帮助。

标签: vbams-word

解决方案


您可以使用该range.GoTo()方法。

Dim rngHead As Range, str_heading_txt As String, hdgn_STYLE As String
Set rngHead = Selection.GoTo(wdGoToHeading, wdGoToPrevious)

'Grab the entire text - headers are considered a paragraph
rngHead.Expand wdParagraph

' Read the text of your heading
str_heading_txt = rngHead.Text

' Read the style (name) of your heading
hdgn_STYLE = rngHead.Style

我注意到您曾经Selection.Sentences(1)抓取文本,但标题本身本质上已经是一个段落 - 所以您可以使用该range.Expand()方法并使用展开wdParagraph


另外,一点建议:

声明变量时,例如:

Dim str_heading_txt, hdgn_STYLE As String

您的意图是好的,但str_heading_txt实际上被声明为 type Variant。不幸的是,对于 VBA,如果您希望您的变量具有特定的数据类型,您需要单独声明:

Dim str_heading_txt As String, hdgn_STYLE As String

或者某些数据类型甚至具有称为类型字符的“速记”方法:

Dim str_heading_txt$, hdgn_STYLE$

请注意如何将$附加到变量的末尾?这只是将其声明为String而不需要As String.

一些常见的类型字符:

  • $细绳
  • &
  • %整数
  • !单身的
  • #双倍的

您甚至可以将这些附加到实际值:

Dim a

a = 5

Debug.Print TypeName(a) 'Prints Integer (default)

a = 5!

Debug.Print TypeName(a) 'Prints Single

推荐阅读