ボタンやリンクをクリックする
操作対象画面(ボタンやリンクの例)を起動
'サンプル3.5.1_ボタンをクリックする
Public Sub clickButton()
Dim ie As InternetExplorer
Dim htdoc As HTMLDocument
Dim InputElements As Object
Dim InputElement As HTMLInputElement
'操作対象Web画面を取得
Set ie = getIE("ボタンやリンクの例")
'ドキュメントを取り出す(参照設定:Microsoft HTML Object Library)
Set htdoc = ie.document
'ドキュメントに含まれるすべてのInput要素を取り出す
Set InputElements = htdoc.getElementsByTagName("INPUT")
'すべてのInput要素内の値を出力する
For Each InputElement In InputElements
If InputElement.Value = "Yahoo!へ" Then
InputElement.Click
Exit For
End If
Next
End Sub
'ドキュメントタイトル/URLを指定してIEを取得
Public Function getIE(arg_title As String, Optional arg_url As String) As Object
Dim ie As Object 'IEを格納する変数(オブジェクト型)
Dim sh As Object '起動中のShellWindow一式を格納する変数
Dim win As Object 'ShellWindowを格納する変数
Dim document_title As String 'ドキュメントタイトルの一時格納変数
Set sh = CreateObject("Shell.Application") 'ShellWindowをwinsに格納
'ShellWindowから1つづつ取得して処理
For Each win In sh.windows
'ドキュメントタイトル取得失敗を無視(処理継続)
On Error Resume Next
document_title = ""
document_title = win.document.Title
On Error GoTo 0
'タイトルバーに引数が含まれるかチェック
If InStr(document_title, arg_title) > 0 Then
Set ie = win '変数ieに取得したwinを格納
Exit For 'ループを抜ける
End If
Next
Set getIE = ie '値の返却
End Function
ボタンはINPUTタグだから、まずはHTML文書からすべてのINPUT要素を取得する。
Set InputElements = htdoc.getElementsByTagName("INPUT")
そのあと、操作対象のボタンを一意に特定する条件を設定して、条件に合致する場合はクリックする。
今回は「Yahoo!へ」と書かれたボタンをクリック対象としているわ。
For Each InputElement In InputElements
If InputElement.Value = "Yahoo!へ" Then
InputElement.Click
誤ったボタンをクリックしないように、Value属性よりもName属性やId属性で指定するほうがベターね。
'サンプル3.5.2_リンクをクリックする
Public Sub clickLink()
Dim ie As InternetExplorer
Dim htdoc As HTMLDocument
Dim Anchors As Object
Dim Anchor As HTMLAnchorElement
'操作対象Web画面を取得
Set ie = getIE("ボタンやリンクの例")
'ドキュメントを取り出す(参照設定:Microsoft HTML Object Library)
Set htdoc = ie.document
'ドキュメントに含まれるすべてのA要素を取り出す
Set Anchors = htdoc.getElementsByTagName("A")
'すべてのA要素内の値を出力する
For Each Anchor In Anchors
If Anchor.innerText = "Googleへ" Then
Anchor.Click
Exit For
End If
Next
End Sub
'ドキュメントタイトル/URLを指定してIEを取得
Public Function getIE(arg_title As String, Optional arg_url As String) As Object
Dim ie As Object 'IEを格納する変数(オブジェクト型)
Dim sh As Object '起動中のShellWindow一式を格納する変数
Dim win As Object 'ShellWindowを格納する変数
Dim document_title As String 'ドキュメントタイトルの一時格納変数
Set sh = CreateObject("Shell.Application") 'ShellWindowをwinsに格納
'ShellWindowから1つづつ取得して処理
For Each win In sh.windows
'ドキュメントタイトル取得失敗を無視(処理継続)
On Error Resume Next
document_title = ""
document_title = win.document.Title
On Error GoTo 0
'タイトルバーに引数が含まれるかチェック
If InStr(document_title, arg_title) > 0 Then
Set ie = win '変数ieに取得したwinを格納
Exit For 'ループを抜ける
End If
Next
Set getIE = ie '値の返却
End Function
考え方はボタンのクリックと同じ。取得対象がAタグになっているのと、条件指定がValue属性ではなくinnerText属性になっている。innerTextとは、リンクが設定された文字列のこと。
INPUT属性の特定にはValue属性よりもName属性やId属性が望ましいように、AタグであればinnerText属性よりもhref属性の方が正確なケースが多いはず。