在IE中打开文档,并能够将其作为变量存储在vbs中

时间:2015-05-14 16:03:46

标签: excel internet-explorer vbscript

我正在尝试编写一个vbs程序,我导航到一个网页,单击一个在excel中打开文件的链接,然后在excel文件中运行一个宏。我知道如何导航到网页并点击链接。我需要帮助找出如何以vbs程序可以操作它的方式存储excel文件。

Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate ("https://www.whateverWebsite.com/")

Dim LinkHref    
LinkHref = "analyze" 'the key word that will be in the link to click
Dim a

For Each a In IE.Document.GetElementsByTagName("a") ' for every element whose tag name starts with 'a' for "a href" pull out its contents
    If InStr((a.GetAttribute("href")), LinkHref)>0 Then 'checks to see if the link that is set contains the string stored in LinkHref
        a.Click 'click the link
    End If
Next

Dim objExcel  
Set objExcel = CreateObject("Excel.Application")

现在如何将我用链接打开的excel文件附加到objExcel?

1 个答案:

答案 0 :(得分:1)

您可以通过GetObject附加到正在运行的Excel实例:

Set xl = GetObject(, "Excel.Application")

如果您启动了多个实例,那么只能获得第一个实例。您必须终止第一个实例才能到达第二个实例。

话虽如此,更好的方法是让Excel直接打开URL:

Set xl = CreateObject("Excel.Application")
For Each a In IE.Document.GetElementsByTagName("a")
    If InStr(a.href, LinkHref) > 0 Then
        Set wb = xl.Workbooks.Open(a.href)
        Exit For
    End If
Next
相关问题