2011-05-09 124 views
3

我在查找單詞中的特定部分時遇到問題。建議我嘗試通過Word中的VB對象瀏覽器尋求幫助。我知道至少有5個標題「集合」(如果你在文檔結構圖中看到I.E.,我會看到編號爲1,2,3,4,5 ...)。我不知道如何導航到第五個標題,最初我認爲它是章節,但是當我查看章節時,我意識到幾乎所有章節都在一個章節中,但是如果有人正在查找有關如何執行章節的信息,以下似乎工作,因爲我已經經歷了寫它的麻煩。獲取Word文檔的特定部分中的段落

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"; 
    } 

所以沒有人知道如何到達第五個標題區域,或者可以指向我可能有所幫助?

+0

我不會回答這個問題,但我只是最終通過段落做了搜索,直到我發現5. <標題文本>幸好大多數人似乎是在多個文件相同的標題,但我仍然會而是能夠跳到第5個「標題1」,如果有人能回答我會很感激。 – onaclov2000 2011-05-11 12:00:26

回答

2

告訴我,如果我沒有正確地關注你,但你正試圖在某個部分找到第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 
+0

這看起來像可能會工作,我可以把它翻譯成perl,當我有一些時間再看一遍,我會回來,讓你知道如果你解決了我的問題! – onaclov2000 2011-06-06 16:43:54

相關問題