VBA:从URL打开一个文本文件来读取

我在我的网站上有一个文本文件,其中只包含string“1.15”(用于我正在编写的应用程序的版本)。 在初始化用户表单时,我想从URL中读取该文件,并返回string“1.15”,以便我可以根据应用程序的版本(存储为常量string)对其进行检查。

这是我想要的格式…

Const version As String = "1.14" Const currentVersionURL As String = "http://mywebsite.com/currentversion.txt" Sub UserForm_Initialize() If version <> GetCurrentVersionNumber() Then MsgBox "Please update the application." End If End Sub Function GetCurrentVersionNumber() As String ' What do I put here? :( End Function 

我知道Workbooks.OpenText方法,但我不想将该string写入工作簿。 我曾尝试使用ADODB.LoadFromFileWinHttp.WinHttpRequest.Open方法,但都无法读取该文件。

任何build议什么填写GetCurrentVersionNumber()与将不胜感激。 🙂

虽然它不能直接回答你的问题,但更简单的方法是使它成为一个XML文件,而不是文本文件。 还有更多的内置工具可以从URL中轻松打开XML文件。 第二个好处是它也使它更加灵活,所以以后你可以更容易地将新的数据元素添加到XML文件中。

例如,如果你创build了一个如下所示的http://mywebsite.com/currentversion.xml文件:

 <?xml version="1.0" encoding="utf-8" ?> <AppData> <Version>1.14</Version> </AppData> 

然后,在VB.NET中,你可以像这样轻松地读取它:

 Function GetCurrentVersionNumber() As String Dim doc As New XmlDocument() doc.Load("http://mywebsite.com/currentversion.xml") Return doc.SelectSingleNode("/AppData/Version").InnerText End Function 

或者,在VBA中,你可以这样读:

 Function GetCurrentVersionNumber() As String Dim doc As MSXML2.DOMDocument?? ' Where ?? is the version number, such as 30 or 60 Set doc = New MSXML2.DOMDocument?? doc.async = False doc.Load("http://mywebsite.com/currentversion.xml") GetCurrentVersionNumber = doc.SelectSingleNode("/AppData/Version").Text End Function 

您将需要添加对Microsoft XML,v?的引用 图书馆,虽然。

试试这个( UNTESTED

 Option Explicit Private Declare Function URLDownloadToFile Lib "urlmon" _ Alias "URLDownloadToFileA" (ByVal pCaller As Long, _ ByVal szURL As String, ByVal szFileName As String, _ ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _ (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long Private Const MAX_PATH As Long = 260 Const currentVersionURL As String = "http://mywebsite.com/currentversion.txt" Const version As String = "1.14" Dim Ret As Long Sub UserForm_Initialize() If version <> GetCurrentVersionNumber() Then MsgBox "Please update the application." End If End Sub Function GetCurrentVersionNumber() As String Dim strPath As String '~~> Destination for the file strPath = TempPath & "currentversion.txt" '~~> Download the file Ret = URLDownloadToFile(0, currentVersionURL, strPath, 0, 0) '~~> If downloaded If Ret = 0 Then Dim MyData As String, strData() As String Open "C:\MyFile.Txt" For Binary As #1 MyData = Space$(LOF(1)) Get #1, , MyData Close #1 GetCurrentVersionNumber = MyData Else MsgBox "Unable to download the file" GetCurrentVersionNumber = "" End If End Function '~~> Get Users Temp Path Function TempPath() As String TempPath = String$(MAX_PATH, Chr$(0)) GetTempPath MAX_PATH, TempPath TempPath = Replace(TempPath, Chr$(0), "") End Function