VBA:从URL打开文本文件以进行读取

tom*_*afe 3 excel vba excel-vba

我的网站上有一个文本文件,只包含字符串"1.15"(我正在编写的应用程序版本).在初始化用户表单时,我想从其URL读取该文件并返回字符串"1.15",以便我可以根据应用程序的版本(存储为const字符串)进行检查.

这是我想要的格式......

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
Run Code Online (Sandbox Code Playgroud)

我知道该Workbooks.OpenText方法,但我不想将字符串写入工作簿.我尝试过使用ADODB.LoadFromFileWinHttp.WinHttpRequest.Open方法,但两者都无法读取文件.

任何有关填写内容的建议GetCurrentVersionNumber()都将不胜感激.:)

Ste*_*art 7

虽然它没有直接回答您的问题,但更简单的方法是将其设为XML文件而不是文本文件.有更多内置工具可以轻松地从URL打开XML文件.第二个优点是它还使其更加灵活,因此您可以在以后更轻松地将新数据元素添加到XML文件中.

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

<?xml version="1.0" encoding="utf-8" ?>
<AppData>
    <Version>1.14</Version>
</AppData>
Run Code Online (Sandbox Code Playgroud)

然后,在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
Run Code Online (Sandbox Code Playgroud)

或者,在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
Run Code Online (Sandbox Code Playgroud)

您需要添加对Microsoft XML的引用,v ?.?但是,图书馆.