2017-05-24 53 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瀏覽器中的選項卡並將其設置爲活動窗口。因此,如果我自動化的標籤位於後臺,我將如何將它帶到前臺並在瀏覽器中顯示標籤的內容? –