vba: return page number from selection.find using text from array

后端 未结 1 604
面向向阳花
面向向阳花 2021-01-18 08:14

(Note: See below for solution.)

I have been trying to retrieve the page numbers from pages that various headings reside on in a word document using VBA. My current

1条回答
  •  再見小時候
    2021-01-18 08:22

    It looks like Selection.Information(wdActiveEndPageNumber) will fit the bill, although it's in the wrong point of your code currently. Put this line after you execute the find, like so:

    For Each hds In astrHeadings
        docSource.Activate
        With Selection.Find
            .Text = Trim$(hds)
            .Forward = True
        End With
        Selection.Find.Execute
        MsgBox hds & ":" & Selection.Information(wdActiveEndPageNumber), vbOKOnly
    Next
    

    Addition for new question:

    When you're setting the strFooter values, you're using ReDim to resize the array when you should be using ReDim Preserve:

    ReDim Preserve strFootNum(1 To UBound(astrHeadings))
    

    But, unless UBound(astrHeadings) is changing during the For loop in question, it'd probably be best practice to pull the ReDim statement outside of the loop:

    ReDim strFootNum(0 To UBound(astrHeadings))
    For i = 0 To UBound(astrHeadings)
        With Selection.Find
            .Text = Trim(astrHeadings(i))
            .Wrap = wdFindContinue
        End With
    
        If Selection.Find.Execute = True Then
            strFootNum(i) = Selection.Information(wdActiveEndPageNumber)
        Else
            strFootNum(i) = 0 'Or whatever you want to do if it's not found'
        End If
        Selection.Move  
    Next
    

    For reference, the ReDim statement sets all the items in an array back to 0, whereas ReDim Preserve preserves all the data in the array before you resize it.

    Also note the Selection.Move and the .Wrap = wdFindContinue lines - I think these were the root of the issue with my previous suggestions. The selection would be set to the final page because the find wasn't wrapping on any run of this other than the first run.

    0 讨论(0)
提交回复
热议问题