EXCEL VBA - 从网站打开文本文件

时间:2009-10-26 07:59:19

标签: vba excel-vba excel

我想阅读来自www.site.com/example.txt等网站的文本文件,并相应地更新Excel工作表中的选项卡。是否可以使用excel VBA?你能告诉一些例子吗?

你能告诉我需要阅读的内容,以便能够实现。是否有一些onlien教程或材料可用。请帮忙

下面的网站有一个如何在JAVA中这样做的例子。有没有人有VBA的例子?

http://www.daniweb.com/forums/thread143010.html#

4 个答案:

答案 0 :(得分:7)

以下是如何下载文本文件的示例。

需要引用Microsoft WinHTTPServices

Sub Test_DownloadTextFile()
    Dim text As String
    text = DownloadTextFile("http://stackoverflow.com/")

    'At this point you can process you file how you wish.
    Debug.Print text
End Sub

'Tool.References... Add a reference to Microsoft WinHTTPServices
Public Function DownloadTextFile(url As String) As String
    Dim oHTTP As WinHttp.WinHttpRequest
    Set oHTTP = New WinHttp.WinHttpRequest
    oHTTP.Open Method:="GET", url:=url, async:=False
    oHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    oHTTP.setRequestHeader "Content-Type", "multipart/form-data; "
    oHTTP.Option(WinHttpRequestOption_EnableRedirects) = True
    oHTTP.send

    Dim success As Boolean
    success = oHTTP.waitForResponse()
    If Not success Then
        Debug.Print "DOWNLOAD FAILED!"
        Exit Function
    End If

    Dim responseText As String
    responseText = oHTTP.responseText

    Set oHTTP = Nothing

    DownloadTextFile = responseText
End Function

答案 1 :(得分:5)

看看Workbooks.OpenText method。 filename参数将接受http URL。该方法允许您在一个步骤中打开并解析它(假设它是一个分隔文件)。

Application.Workbooks.OpenText("http://somewebsite.com/test.txt", _
  StartRow:=3, _
  DataType:=Excel.XlTextParsingType.xlDelimited, _
  TextQualifier:=Excel.XlTextQualifier.xlTextQualifierNone, _
  Comma:=True)

答案 2 :(得分:0)

是的,你可以使用例如http客户端库来从网上获取页面。

还有可用的工具或此类任务 http://www.iopus.com/iMacros/excel.htm?ref=rg8excel1HB&gclid=CLWbrNef2p0CFUtp4wodBnx8sQ

如果你想自己动手,你必须参考 “Microsoft Internet Transfer”Active X控件。

例如,您可以使用获取页面 buf = HTTPControl.OpenURL(page_you_like_to_fetch,icByteArray) 然后你可以用通常的“嫌疑人”打开它 打开或您可以将文件注册为ODBC源并使用它来获取它 SQL语句。

当然你也可以手工完成。打开文件,逐个访问一个条目并将其放入正确的Execl单元格中。

答案 3 :(得分:0)

我喜欢Friedrich的建议,但是如果您想以另一种方式执行此操作,则可以使用VBA中的shell命令启动此过程:

Windows Implementation of the Linux WGet command

这是Linux命令的一个端口,它从命令行获取文件的网站内容(URL),然后就可以打开在VBA代码中本地创建的文件并处理它相应

(此命令可能还有其他实现,我只是链接到我在Google上找到的第一个实现)