(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
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.