Wordマクロで選択位置のページ番号を取得する場合、簡単なのはSelectionオブジェクトのInformationプロパティを使う方法です。
Public Sub Sample01()
With Selection
MsgBox "指定した選択範囲または指定範囲の終了位置のページ番号:" & _
.Information(wdActiveEndPageNumber) & vbNewLine & _
"手動で変更したページ番号を反映:" & _
.Information(wdActiveEndAdjustedPageNumber) & vbNewLine & _
"総ページ数:" & _
.Information(wdNumberOfPagesInDocument)
End With
End Sub

Informationプロパティの引数(WdInformation)による違いは下記の通りで、状況に応じて使い分けをします。
- wdActiveEndPageNumber:指定した選択範囲または指定範囲の終了位置のページ番号を取得します。
- wdActiveEndAdjustedPageNumber:指定した選択範囲または指定範囲の終了位置のページ番号を取得します。セクションを区切って手動でページ番号を振り直した場合は、変更後のページ番号を取得します。
- wdNumberOfPagesInDocument:総ページ数を取得します。
先日、MSDNフォーラムに「Word VBAで、カーソル位置とは関係なくステータスバーに表示されているページ番号を取得するにはどうすれば良いか?」という質問がありました。
たしかに、ステータスバーをよく見てみると、スクロール位置によっては微妙に上記マクロで取得できる番号とは異なるページ番号が表示されています。
この“ステータスバーに表示されているページ番号”の需要がどこまであるのかは分かりませんが、UIAutomationを使って無理やり取得するコードを考えてみました。
'UIAutomationClient(UIAutomationCore.dll)要参照
Option Explicit
Public Sub Sample02()
'ステータス バーからページ番号取得
'※「ステータス バー」と「ページ番号」が表示されていることが前提
Dim uiAuto As UIAutomationClient.CUIAutomation
Dim elm As UIAutomationClient.IUIAutomationElement
Dim ary As IUIAutomationElementArray
Dim acc As Office.IAccessible
Dim num As String
Dim v As Variant
Dim i As Long
'ステータス バーからIAccessible経由でIUIAutomationElement取得
Set acc = Application.CommandBars("Status Bar")
Set uiAuto = New UIAutomationClient.CUIAutomation
Set elm = uiAuto.ElementFromIAccessible(acc, 0)
'ステータス バー(NetUInetpane)取得
Set elm = GetElement(uiAuto, elm, UIA_ClassNamePropertyId, "NetUInetpane")
'子要素からCurrentNameに[ページ番号]が含まれるものを取得
Set ary = elm.FindAll(TreeScope_Subtree, uiAuto.CreateTrueCondition)
For i = 0 To ary.Length - 1
num = ary.GetElement(i).CurrentName
If InStr(num, "ページ番号") Then Exit For
Next
'取得したページ番号整形
num = Replace(num, "ページ番号", "")
num = Replace(num, "ページ", "")
num = Trim(num)
v = Split(num, "/")
MsgBox "ページ番号:" & v(LBound(v)) & vbNewLine & _
"総ページ数:" & v(UBound(v)), vbInformation + vbSystemModal
End Sub
Private Function GetElement(ByVal uiAuto As CUIAutomation, _
ByVal elmParent As IUIAutomationElement, _
ByVal propertyId As Long, _
ByVal propertyValue As Variant, _
Optional ByVal ctrlType As Long = 0) As IUIAutomationElement
Dim cndFirst As IUIAutomationCondition
Dim cndSecond As IUIAutomationCondition
Set cndFirst = uiAuto.CreatePropertyCondition( _
propertyId, _
propertyValue _
)
If ctrlType <> 0 Then
Set cndSecond = uiAuto.CreatePropertyCondition( _
UIA_ControlTypePropertyId, _
ctrlType _
)
Set cndFirst = uiAuto.CreateAndCondition( _
cndFirst, _
cndSecond _
)
End If
Set GetElement = elmParent.FindFirst(TreeScope_Subtree, cndFirst)
End Function

ステータスバーに「ページ番号」が表示されていることが前提となりますが、これで一応取得できるようになりました。
もしかしたら、もっと簡単な方法があるかもしれませんが、とりあえず今回はこれで良しとします。



















この記事へのコメントはありません。