2014-10-28 31 views
0

我試圖列出文檔中的「標題1」樣式的每個實例(最終將它們列在窗體上的組合框中)。列出「標題1」樣式的所有實例

以下代碼似乎找到「標題1」的實例,因爲在即時窗口中列出的條目數是正確的,但.text不返回任何內容。

我在做什麼錯?謝謝。

Dim blnFound As Boolean 
Dim i as Integer 

i = 1 

With ThisDocument.Range.Find 
    .Style = "Heading 1" 

    Do 
     blnFound = .Execute 
     If blnFound Then 
      Debug.Print i & " " & .Text 
      i = i + 1 
     Else 
      Exit Do 
     End If 
    Loop 
End With 

回答

2

我不相信你的對象有一個.Text屬性。選擇具有.Text屬性。試試這個:

Sub FindHeadings() 
' October 28, 2014 
Dim blnFound As Boolean 
Dim i As Integer 
i = 1 
' Set up the find conditions 
Selection.HomeKey Unit:=wdStory 
Selection.Find.ClearFormatting 
Selection.Find.Style = ActiveDocument.Styles("Heading 1") 
With Selection.Find 
    .Text = "" 
    .Replacement.Text = "" 
    .Forward = True 
    .Wrap = wdFindContinue 
    .Format = True 
    .MatchCase = False 
    .MatchWholeWord = False 
    .MatchWildcards = False 
    .MatchSoundsLike = False 
    .MatchAllWordForms = False 
End With 
Selection.Find.Execute 
Selection.MoveLeft Unit:=wdCharacter, count:=1 

'Repeat while you find the style 
blnFound = True 
While blnFound 
    With Selection.Find 
     .Execute 
     If .Found = True Then 
       Debug.Print i & " " & Selection.Text 
       i = i + 1 
      ' Move to the next character 
      Selection.MoveRight Unit:=wdCharacter, count:=1 
     Else 
      Debug.Print "Done" 
      blnFound = False 
     End If 
    End With 
Wend 
End Sub 
+0

謝謝,這是行得通的。現在我不幸地遇到了一個新問題 - 我的文檔中有一個目錄,您的解決方案正在選擇該文檔中的標題。你知道一種防止這種情況的方法嗎?謝謝。 – 2014-10-29 11:17:16

+0

我不知道您的目錄的標題是否也使用標題1樣式?如果是這樣,我建議爲該標題使用(或創建)不同的樣式,這樣宏不會被拾取。 (注意,我剛剛在代碼中增加了一行代碼)。 – Jeff1265344 2014-10-30 17:37:16

相關問題