条件に合致するフレームの検索
フレームの例画面を起動'サンプル4.1.2.1_条件に合致するフレームの検索(失敗ケース) Public Sub getFrame2() Dim ie As InternetExplorer Dim fra As HTMLFrameElement Set ie = getIE("フレームの例") 'IE取得 'コレクション内のフレームに対して逐次処理 For Each fra In ie.document.frames '内部HTMLドキュメントのタイトルが「フレーム3の中身」の場合に処理 If fra.Document.TItle = "フレーム3の中身" Then 'ドキュメント中の特定項目の値を取得して表示 MsgBox fra.document.forms("TargetForm").elements("TargetText").Value Exit For End If DoEvents 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
ある画面要素が特定の条件に合致するとき処理する場合、特定要素をコレクションとして取得したうえでFor Eachで逐次処理...というロジックを組むことが多い。
でもFramesメソッドの戻り値は通常のコレクションと同様に扱うことができない。理由はよくわからないわ。ワークアラウンドとして、私は次のサンプルコードのように処理している。
For Each fra In ie.document.frames
たとえばこのようなコードね。でもFramesメソッドの戻り値は通常のコレクションと同様に扱うことができない。理由はよくわからないわ。ワークアラウンドとして、私は次のサンプルコードのように処理している。
'サンプル4.1.2.2_条件に合致するフレームの検索 Public Sub getFrame3() Dim ie As InternetExplorer Dim i As Integer Set ie = getIE("フレームの例") 'IE取得 'フレーム数分処理する(Lengthは自然数だが、Indexは0からのため-1する) For i = 0 To ie.document.frames.Length - 1 '内部HTMLドキュメントのタイトルが「フレーム3の中身」の場合に処理 If ie.document.frames(i).Document.Title = "フレーム3の中身" Then 'ドキュメント中の特定項目の値を取得して表示 MsgBox ie.document.frames(i).document.forms("TargetForm").elements("TargetText").Value Exit For End If DoEvents 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
フレームの特定はFramesメソッドの引数としてフレーム名(FRAMEタグのName属性)のほか、インデックス値でも指定することができる。その特性を利用してループカウンタを使って逐次処理する。
For i = 0 To ie.document.frames.Length - 1 If ie.document.frames(i).Document.Title = "フレーム3の中身" ThenLengthで取得できる結果はフレーム数(=自然数)になるのに対して、インデックス値は0からはじまるから、ループの回数はLength - 1になる点に注意が必要よ。