ray88’s diary

お仕事で困ったとき用の自分用の覚書

IE操作 タイトルを指定して起動済みのIEを取得する

(例)開いているwebページで タイトルが「Google」のIEを取得する

Sub SearchIE()
    Dim colSh As Object
    Dim win As Object
    Dim strTemp As String
    Dim objIE As Object
    Set colSh = CreateObject("Shell.Application")
    For Each win In colSh.Windows    
        If TypeName(win.document) = "HTMLDocument" Then        
            If InStr(win.document.Title, "Google") > 0 Then
                Set objIE = win
                Exit For
            End If
        End If
    Next    
    If objIE Is Nothing Then
        MsgBox "検索対象のIEはありませんでした"
    Else
        MsgBox objIE.document.Title & "がありました"
    End If
End Sub

その2

Sub SearchIE2()
    Dim colSh As Object
    Dim win As Object
    Dim strTemp As String
    Dim objIE As Object
    Set colSh = CreateObject("Shell.Application")
    For Each win In colSh.Windows
        strTemp = ""        
        On Error Resume Next
        strTemp = win.document.Title
        On Error GoTo 0
        If InStr(strTemp, "Google") > 0 Then
            Set objIE = win
            Exit For
        End If
    Next    
    If objIE Is Nothing Then
        MsgBox "検索対象のIEはありませんでした"
    Else
        MsgBox objIE.document.Title & "がありました"
    End If
End Sub

同一のタイトルを持つページが複数表示されている場合等、タイトルのみで絞れない場合はIEが持つ他の属性を指定して判定する。URLやドキュメント内の文字列等

        'URLで判定する場合
        strTemp = win.LocationURL
        'テキストが取得できない場合も処理を続行
        On Error Resume Next
        'ドキュメント中に存在する文字列で判定する場合
        strTemp = win.Document.body.innertext
        On Error GoTo 0
        'ページ上に文字列「アップデート情報」が存在するか判定
        If InStr(strTemp, "BBQ") > 0 Then
        '変数objIEに取得したwinを格納
            Set objIE = win
        'ループを抜ける
            Exit For
        End If