使用VBA单击在线excel下载按钮



我的目标是点击这个网站上的excel下载按钮。我一直收到"自动化错误"。在我的while循环中,接口是未知的。


Sub GetData()
Dim IE As InternetExplorerMedium
Dim HTMLDoc As HTMLDocument
Dim objElement As HTMLObjectElement
Set IE = New InternetExplorerMedium
With IE
.Visible = True
.Navigate "https://www.pimco.com/en-us/investments/mutual-funds"
Do While .readyState = 4: DoEvents: Loop
Do Until .readyState = 4: DoEvents: Loop
.document.getElementById("csvLink").Click
End With
Set IE = Nothing
End Sub

这里有一些函数可以用来帮助清理代码。https://stackoverflow.com/a/59721369/12685075

我不会试图把这些都塞进With子句中。

我会考虑把每一步都分成它自己的带有函数的部分。

然后检查就绪状态,并确保元素存在,首先使用错误处理,然后单击它

话虽如此,我想说,您可能可以跳过IE资源管理器加载,直接使用XMLHTTP请求获取链接。因此,在chrome中打开页面,打开DevTools,刷新页面,下载CSV,并开始查看网络请求。

您会找到一个代表下载文件的链接,它很可能是一个直接链接,然后您可以将其与参数一起使用,让XMLHTTP跳过页面内容,每次都可以获得文件,而无需担心CSS/formating/fonths等加载元素。

运行出现问题的一些解释:

  • 不要使用InternetExplorerMedium
    • 这里的问题是IE被打开了两次。第一次打开后,它会立即再次关闭,并在另一个实例中加载URL。但该实例不再分配给IE变量,宏也不能引用该实例。您可以在执行宏时观察到这一点。IE好像抽搐过一次
  • 线路CCD_ 2和CCD_。
    • 4表示页面已完全加载。所以您可以使用Do While .readyState <> 4: DoEvents: LoopDo Until .readyState = 4: DoEvents: Loop。两个循环中的一个就足够了
  • IE报告完成后,页面加载动态内容。
    • 因此,您必须中断,直到加载该内容为止。要做到这一点,最简单的方法就是硬闯。看看下面代码中的那个部分
  • 您必须触发下载。
    • 要做到这一点,您需要Sendkeys((。这不是一件好事,但在这里是不可避免的。我不认为像Peyter所假设的那样有直接的下载链接,因为我认为下载文件只是根据页面显示的数据根据请求生成的。至少这是我对此类下载的体验
    • 请阅读我在Sendkeys((行上方写的宏中的注释,然后在您的计算机上找到下载的文件

以下是有效的代码:

Sub GetData()
Dim IE As Object

Set IE = CreateObject("internetexplorer.application")
IE.Visible = True
IE.Navigate "https://www.pimco.com/en-us/investments/mutual-funds"
Do Until IE.readyState = 4: DoEvents: Loop
'Manual break to load dynamic content after
'the IE reports the ready state 'complete' (4)
'The last three values are hours, minutes, seconds
Application.Wait (Now + TimeSerial(0, 0, 10))

'Now we can click the button
IE.document.getElementById("csvLink").Click

'Here you need sendkeys to trigger the save button
'Don't touch anything while the code runs
'Sendkeys will send the key combination in the brackets
'to the application which has the focus
'The file will be saved to your standard donload directory
'or to the download directory you placed in the IE settings
'if you did that
Application.SendKeys ("%{S}")

'Clean up
IE.Quit
Set IE = Nothing
End Sub

最新更新