Set Focus to Internet Explorer Object in Visual Basic

Lloyd Banks picture Lloyd Banks · Jun 25, 2012 · Viewed 24.4k times · Source

Does anybody know how to set focus onto an IE object with Visual Basic? I've tried myieobject.SetFocus, but the compiler errors with this statement.

Answer

Mike Lewis picture Mike Lewis · Jun 26, 2014

I needed a spreadsheet of mine to "set focus" to Internet Explorer after performing a function so I didn't have to bother clicking on it. This is what I found to work:

      Const myPageTitle As String = "Title of my webpage"
      Const myPageURL As String = "http://www.mywebpage.com"
      Dim myIE As SHDocVw.InternetExplorer
      Dim myIE As InternetExplorer
      Set myIE = GetOpenIEByTitle(myPageTitle, False)


      myIE.visible = false
      DoEvents
      myIE.visible = true  
     'for some reason, making the page invisible then visible always ensures it pops up

    Function GetOpenIEByTitle(i_Title As String, _
                          Optional ByVal i_ExactMatch As Boolean = True) As SHDocVw.InternetExplorer
Dim objShellWindows As New SHDocVw.ShellWindows

  If i_ExactMatch = False Then i_Title = "*" & i_Title & "*"
  'ignore errors when accessing the document property
  On Error Resume Next
  'loop over all Shell-Windows
  For Each GetOpenIEByTitle In objShellWindows
    'if the document is of type HTMLDocument, it is an IE window
    If TypeName(GetOpenIEByTitle.document) = "HTMLDocument" Then
      'check the title
      If GetOpenIEByTitle.document.Title Like i_Title Then
        'leave, we found the right window
        Exit Function
      End If
    End If
  Next
End Function