VBA自定义函数:获取指定单元格所在的页码

标签:VBA

下面的自定义函数可以获取指定单元格所在的页码:

代码语言:javascript
复制
Public Function PageNumber( _
       Optional ByRef target As Excel.Range, _
       Optional ByVal nStart As Long = 1&) As Variant
 Dim pbHorizontal As HPageBreak
 Dim pbVertical As VPageBreak
 Dim nHorizontalPageBreaks As Long
 Dim nPageNumber As Long
 Dim nVerticalPageBreaks As Long
 Dim nRow As Long
 Dim nCol As Long

On Error GoTo ErrHandler
Application.Volatile
If target Is Nothing Then _
Set target = Application.Caller
With target
nRow = .Row
nCol = .Column
With .Parent
If .PageSetup.Order = xlDownThenOver Then
nHorizontalPageBreaks = .HPageBreaks.Count + 1&
nVerticalPageBreaks = 1&
Else
nHorizontalPageBreaks = 1&
nVerticalPageBreaks = .VPageBreaks.Count + 1&
End If
nPageNumber = nStart
For Each pbHorizontal In .HPageBreaks
If pbHorizontal.Location.Row > nRow Then Exit For
nPageNumber = nPageNumber + nVerticalPageBreaks
Next pbHorizontal
For Each pbVertical In .VPageBreaks
If pbVertical.Location.Column > nCol Then Exit For
nPageNumber = nPageNumber + nHorizontalPageBreaks
Next pbVertical
End With
End With
PageNumber = nPageNumber
ResumeHere:
Exit Function
ErrHandler:
PageNumber = CVErr(xlErrRef)
Resume ResumeHere
End Function

可以这样调用上面的自定义函数:

= PageNumber(Cell, Start)

其中,

参数Cell,指定一个单元格,程序将给出这个单元格所在的页码。如果忽略,则为包含公式的单元格。

参数Start,指定起始页码,如果忽略则为1。

下面的测试代码调用该自定义函数获取当前单元格所在的页码:

代码语言:javascript
复制
Sub test()
MsgBox PageNumber(ActiveCell, 1)
End Sub

注:本文的代码来源于mcgimpsey.com,这个网站有些不错的VBA程序,有兴趣的朋友可以去看看。