VBA - 从没有文件名的url下载文件

时间:2016-01-28 20:00:00

标签: excel vba url download

我有一个由https:// servername / parameterList组成的URL。如果我在IE中输入URL,系统会提示我输入用户名/密码,然后选择打开/保存查询结果的文本文件。

我要做的是使用VBA自动获取查询结果,将其保存到文件或将内容返回到变量。我尝试了几种从URL下载文件的方法,包括

How do i download a file using VBA (Without internet explorer)

但是,这会保存包含HTML(关于请求?)的文件,而不是可下载文件中的查询结果。所以我得到的是!DOCTYPE html等,而不是制表符分隔列中的搜索结果表。

我认为上面链接中的示例都有一些您希望在URL末尾下载的文件,因此它是文件/图像的直接链接。

很抱歉,如果有问题可以解决此问题。我不认为我知道这个过程中发生了什么,足以找到有意义的结果。初始URL是重定向的吗?如果结果文件是根据查询动态生成的,有什么方法可以实现吗?感谢。

1 个答案:

答案 0 :(得分:0)

我遇到了和你一样的问题,并且已经使用SendKeys下载了该文件。它不是一个强大的解决方案,我在使用多个版本的IE时遇到了问题,但它完成了工作。

'YourLink is a string of the URL in the form "http://link.com/"

Dim IE As Object
Dim myURL As String

myURL = YourLink

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

IE.navigate myURL

SetWindowPos IE.HWND, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE

'Wait until the web page is fully loaded.

Sleep 1500 'delay in milliseconds

'If they click out of IE, it won't work. This makes sure that if they did, it just stops right there.
If GetForegroundWindow() <> IE.HWND Then
    MsgBox "Please try again and do not click out of the internet explorer window."
    Exit Sub
End If

Sleep 1500

If GetForegroundWindow() <> IE.HWND Then
    MsgBox "Please try again and do not click out of the internet explorer window."
    Exit Sub
End If

'Press keys to download (tabs to save button and then clicks it)

SendKeys "{TAB}", True
SendKeys "{TAB}", True
SendKeys "{ENTER}", True
SendKeys "{ENTER}", True

我非常喜欢编程,这段代码的不同部分都是从其他人那里获得的。其他问题的答案(不幸的是,我没有把它们写下来以适当的信用)。要使用Sleep,GetForegroundWindow()和SetWindowPos函数,您需要找到放入模块的引用(应该很容易找到)。如果您在发布此问题后找到了更好的解决方案,请告诉我们!