ハイパーリンク(aタグ)のクリック
大きなサイトの操作ではボタンのクリックやテキストボックスへの文字入力に比べて使用することは少ないですが、VBAでハイパーリンク(aタグ)をクリックすることも可能です。今回はハイパーリンクをクリックするVBAコードを記載します。
ハイパーリンクをクリックするVBAコード
ハイパーリンクのクリックは「aタグ(リンクタグ)」であることと「表示されている文字列」で認識させます。
objIEに格納されているIEのページにおいて、「○○○」という文字の入ったハイパーリンクをクリックするコードは以下のようになります。
Dim anchor As HTMLAnchorElement
For Each anchor In objIE.document.getElementsByTagName(“A”)
If InStr(anchor.innerText, “○○○”) > 0 Then
anchor.Click
Exit For
End If
Next
For Each anchor In objIE.document.getElementsByTagName(“A”)
If InStr(anchor.innerText, “○○○”) > 0 Then
anchor.Click
Exit For
End If
Next
ポイントは以下の2点です。
①HTMLAnchorElementとして変数を定義する
今回はanchorという変数を用いています。
②If InStr(anchor.innerText, “○○○”) > 0 Thenで文字列が含まれているかを調べる
InStrは1つ目の引数で指定した文字列の中から2つ目の引数で指定した文字列のある場所を教えてくれる関数です。
文字列が含まれていない場合は「0」になるので、上記の式で「○○○」という文字列がハイパーリンクの中に含まれているかを判断することができます。
スポンサーリンク
ハイパーリンクをクリックするVBAコードの例
YahooJapanのトップページから「ショッピング」というハイパーリンクをクリックするVBAコードは以下のようになります。
Declare Sub Sleep Lib “kernel32” (ByVal dwMilliseconds As Long)
Sub yahooのリンクをクリック()
Dim colSh As Object
Dim objIE As InternetExplorer
Dim win As Object
Dim anchor As HTMLAnchorElement
Shell “C:\Program Files\Internet Explorer\iexplore.exe http://www.yahoo.co.jp/”, vbNormalFocus
Sleep 3000
Set colSh = CreateObject(“Shell.Application”)
For Each win In colSh.Windows
If TypeName(win.document) = “HTMLDocument” Then
If InStr(win.document.Title, “Yahoo”) > 0 Then
Set objIE = win
Exit For
End If
End If
Next
If objIE Is Nothing Then
MsgBox “入力するページが見つかりません”
End If
For Each anchor In objIE.document.getElementsByTagName(“A”)
If InStr(anchor.innerText, “ショッピング”) > 0 Then
anchor.Click
Exit For
End If
Next
End Sub
Sub yahooのリンクをクリック()
Dim colSh As Object
Dim objIE As InternetExplorer
Dim win As Object
Dim anchor As HTMLAnchorElement
Shell “C:\Program Files\Internet Explorer\iexplore.exe http://www.yahoo.co.jp/”, vbNormalFocus
Sleep 3000
Set colSh = CreateObject(“Shell.Application”)
For Each win In colSh.Windows
If TypeName(win.document) = “HTMLDocument” Then
If InStr(win.document.Title, “Yahoo”) > 0 Then
Set objIE = win
Exit For
End If
End If
Next
If objIE Is Nothing Then
MsgBox “入力するページが見つかりません”
End If
For Each anchor In objIE.document.getElementsByTagName(“A”)
If InStr(anchor.innerText, “ショッピング”) > 0 Then
anchor.Click
Exit For
End If
Next
End Sub
おすすめ書籍 (広告)
Amazon 楽天 Yahoo検索 |
---|
Amazon 価格:¥1,603円 |
bookfan 1号店 楽天市場店 価格:2,530円 |
bookfan 1号店 楽天市場店 価格:2,530円 |
bookfanプレミアム 価格:2,530円 |
VALUE BOOKS Yahoo!店 価格:413円 |
コメント