【问题标题】:Get Paragraphs in specific Section of Word Document获取 Word 文档特定部分中的段落
【发布时间】:2011-05-09 11:40:28
【问题描述】:

我在查找 word 中的特定部分时遇到问题。建议我尝试通过 Word 中的 VB 对象浏览器寻求帮助。我知道至少有 5 个标题“集”(即,如果您查看文档地图,我看到编号为 1、2、3、4、5...)。我不知道如何导航到第五个标题,最初我以为是部分,但当我查看部分时,我意识到几乎所有部分都在一个部分中,但万一有人正在寻找有关如何做部分的信息,以下似乎可行,因为我已经经历了编写它的麻烦。

my($document) = $Word->Documents->Open($input) || die("Unable to open document ", Win32::OLE->LastError());
my $section = $document->{Sections}->Item(1); # put section number you're looking for in here
$section_five_paragraphs = $section->{Range}->Paragraphs();
$enumerate = new Win32::OLE::Enum($section_five_paragraphs); 
  while (defined($paragraph = $enumerate->Next()))
  {
     print $paragraph->{Range}->{Text} . "\n";
  }

那么有谁知道如何到达第 5 个标题区域,或者可以指出一些可能有帮助的东西吗?

【问题讨论】:

  • 我不会回答这个问题,但我只是通过段落进行搜索,直到找到 5 个。幸运的是,其中大多数似乎在多个文档中都是相同的标题,但是我仍然希望能够跳到第 5 个“标题 1”,如果有人能回答我将不胜感激。

标签: perl ms-word ole


【解决方案1】:

如果我没有正确关注您,但您试图在某个部分中找到第 5 个标题 1,请告诉我?如果是这种情况,虽然 Word 明确定义了部分(您记为 $document->{Sections}->Item(1)),但它并没有明确定义特定的标题或一般的样式。为此,您必须浏览所有样式以寻找感兴趣的样式。下面的 VBA 代码(我很抱歉没有编写 perl)就是这样做的,并且只在特定部分中显示。

Sub FindHeading1()
    On Error GoTo MyErrorHandler

    Dim currentDocument As Document
    Set currentDocument = ActiveDocument

    Dim findRange As Range
    Set findRange = currentDocument.Sections(2).Range 'which section you want

    Dim endRange As Long
    endRange = findRange.end

    findRange.Find.ClearFormatting
    findRange.Find.Style = ActiveDocument.Styles("Heading 1")

    Dim headingCountFound As Long
    Do While findRange.Find.Execute(FindText:="")
        If findRange.End > endRange Then Exit Sub
        findRange.Select
        headingCountFound = headingCountFound + 1
        If headingCountFound = 3 Then 'which occurance you want
            MsgBox "Found."
            Exit Do
        End If

        DoEvents
    Loop

    Exit Sub

MyErrorHandler:
    MsgBox "FindHeading1" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub

【讨论】:

  • 这看起来可能行得通,我大概可以把它翻译成perl,当我有时间再看一遍时,我会回来告诉你如果你解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多