2017-12-27 450 views
0

我希望我的宏在單獨的IE選項卡中打開存儲在電子表格中的每個鏈接。我是成功的,打開第一個鏈接,但在循環的第二次迭代某種原因,我得到:在新標籤頁中打開多個鏈接的宏

自動化和error.The接口是未知 錯誤。

我懷疑宏在第一次迭代後失去IE對象引用,但我不知道爲什麼。

範圍設置OK。

下面是代碼:

Sub OpenCodingForms() 

Dim wb1 As Workbook 
Dim ws1 As Worksheet 
Dim CodingFormLinks As Range 
Dim IE as InternetExplorerMedium 

Set wb1 = Workbooks("New shortcut.xlsm") 
Set ws1 = wb1.Worksheets("Data") 
Set CodingFormLinks = ws1.Range("A2", Range("A2").End(xlDown)) 
Set IE = CreateObject("InternetExplorer.Application") 

IE.Visible = True 

ws1.Activate 

For Each link In CodingFormLinks.Cells 
    IE.Navigate link, CLng(2049) 
Next link 

End Sub 
+0

我得到多個窗口打開,如果我定義鏈接的範圍,並導航到Link.Text,如果我用2048我可以讓他們在現有窗口的新選項卡中打開。 – QHarr

+3

嘗試CLng(2048)而不是CLng(2049),您也可以嘗試在循環中嘗試延遲以允許頁面加載 - 而IE.Busy |做事件| Wend – Absinthe

+0

我嘗試了所有的建議,但無濟於事,仍然是同樣的錯誤。但是,如果我在循環內移動「設置IE」和「IE.Visible」,我設法打開新窗口中的所有鏈接,但這不是首選解決方案。 – barciewicz

回答

0

我就遇到了這個問題之前,最終只是寫一個程序來獲得實例。您將需要添加對shell控件和自動化的引用。

如果存在重定向,您可能需要調整此選項以在實際URL的開頭查找sURL var。

Sub OpenCodingForms() 

Dim wb1 As Workbook 
Dim ws1 As Worksheet 
Dim CodingFormLinks As Range 
Dim IE As InternetExplorerMedium 

    Set wb1 = Workbooks("New shortcut.xlsm") 
    Set ws1 = wb1.Worksheets("Data") 
    Set CodingFormLinks = ws1.Range("A2", Range("A2").End(xlDown)) 
    Set IE = CreateObject("InternetExplorer.Application") 

    IE.Visible = True 
    ws1.Activate 

    Dim sUrl As String 
    For Each link In CodingFormLinks.Cells 
     sUrl = link.Value 
     IE.navigate sUrl, CLng(2048) 
     Set IE = GetWebPage(sUrl) 
    Next link 

End Sub 



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
'Desc: The Function gets the Internet Explorer window that has the current 
' URL from the sURL Parameter. The Function Timesout after 30 seconds 
'Input parameters: 
    'String sURL - The URL to look for 
'Output parameters: 
    'InternetExplorer ie - the Internet Explorer window holding the webpage 
'Result: returns the Internet Explorer window holding the webpage 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
Function GetWebPage(sUrl As String) As InternetExplorer 
Dim winShell As Shell 
Dim dt As Date 
    'set the timeout period 
    dt = DateAdd("s", 300, DateTime.Now) 

Dim IE As InternetExplorer 
    'loop until we timeout 
    Do While dt > DateTime.Now 
     Set winShell = New Shell 
     'loop through the windows and check the internet explorer windows 
     For Each IE In winShell.Windows 
      'check for the url 
      If IE.LocationURL = sUrl Then 
       'set the window visible 
       IE.Visible = True 
       IE.Silent = True 
       'set the return value 
       Set GetWebPage = IE 
       Do While IE.Busy 
        DoEvents 
       Loop 
       Set winShell = Nothing 
       Exit Do 
      End If 
     Next IE 
     Set winShell = Nothing 
     DoEvents 
    Loop 
End Function 
相關問題