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

雨燕双飞 提交于 2019-12-01 18:07:46

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!