2017-05-24 274 views
0

假设我有下面的代码片段:激活后台标签页在Internet Explorer中使用VBA

Option Explicit 

Sub Main() 
    Dim IE As Object 
    Set IE = GetIE("http://www.google.com") 

    ' Need tabbed page for google.com to come to the foreground 

End Sub 

GetIE功能下面参考

Function GetIE(sLocation As String) As Object 

    Dim objShell As Object, objShellWindows As Object, o As Object 
    Dim sURL As String 
    Dim retVal As Object 

    Set retVal = Nothing 
    Set objShell = CreateObject("shell.application") 
    Set objShellWindows = objShell.Windows 

    For Each o In objShellWindows 
     sURL = "" 
     On Error Resume Next 
     'check the URL and if it's the one you want then 
     'assign it to the return value and exit the loop 
     sURL = o.document.location 
     On Error GoTo 0 
     If sURL Like sLocation & "*" Then 
      Set retVal = o 
      Exit For 
     End If 
    Next o 

    Set GetIE = retVal 

End Function 

随着我使用GetObject而不是CreateObject我可能会遇到这样的情况,即我的对象实际上是Internet Explorer应用程序中的一个选项卡。

这个问题是出于我的自动化目的,我通常在任何时候都打开相当多的选项卡。我将如何去使IE对象带标签页www.google.com到前台(使其成为可见标签)?我试过IE.Activate,IE.Visible = True,IE.Document.Focus,并且无法获得我需要的结果。

我还应该补充一点,我可以用我需要的任何其他方式来操作选项卡(IE.Navigate以及使用getElementByID的挂钩元素),而不必将它作为Internet Explorer应用程序中的可见选项卡。

回答

0

下面是我用来获取对Internet Explorer窗口的现有实例的引用,无论它是独立窗口还是选项卡。

我注意到的一个区别是您可能想要使用LocationURLLocationName属性来识别窗口。我似乎无法在Internet Explorer的文档中找到Location属性(但我可能错过了它),所以这可能是您面临的问题的一部分。

Function getIE(SearchBy As String, SearchCriteria As String) As Object 
On Error GoTo Errhand: 

    Dim Window As Object 

    For Each Window In CreateObject("Shell.Application").Windows 
     If SearchBy = "URL" And Window.LocationUrl Like "*" & SearchCriteria & "*" Then 
      Set getIE = Window 
      Exit Function 
     ElseIf SearchBy = "Name" And Window.LocationName Like "*" & SearchCriteria & "*" Then 
      Set getIE = Window 
      Exit Function 
     End If 
    Next 

CleanExit: 
    Set getIE = Nothing 
    Exit Function 

Errhand: 
    'Add error handling/messaging here 
    Resume CleanExit 
End Function 

上述代码的工作方式与您共享的代码非常相似。一个重要的特点是,如果找不到匹配项,则该对象将返回为Nothing

Sub SOIE_Example() 
    Dim IE As Object 
    Set IE = getIE("URL", "google") 

    If IE Is Nothing Then 
     MsgBox ("Couldn't find the IE window with the title google") 
     Exit Sub 
    Else 
     'Do what you need with the object/website here 
    End If 
End Sub 

一旦你到窗口的引用它不需要激活的说使用这部分的方法:因此,它集成到你的代码中检查这个时候是很重要的,你可以做到这一点Internet Explorer对象。你可以更新一个HTMLElement的值,innerText,点击一个链接/按钮等,所有这些窗口都没有被激活。

+0

我对设置对象没有任何问题,我只需要知道如何激活IE浏览器中的选项卡并将其设置为活动窗口。因此,如果我自动化的标签位于后台,我将如何将它带到前台并在浏览器中显示标签的内容? –