You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:VBA中除Msxml2.ServerXMLHTTP外的HTTP GET请求替代方案

问题

我正尝试在VBA宏中调用API,使用的代码如下:

Dim objRequest As Object
Set objRequest = CreateObject("Msxml2.ServerXMLHTTP.6.0")
   
With objRequest
    .Open "GET", "somewebpage", True
    .setRequestHeader "Cache-Control", "no-cache"
    .setRequestHeader "Pragma", "no-cache"
    .Send
    While objRequest.readyState <> 4
        DoEvents
    Wend
    Debug.Print .responseText
End With
Set objRequest = Nothing

上述代码在多数Excel版本(2007/10/13/16/19/365)中运行正常,但在特定版本——Excel 2013 (15.0.4569.1504) MSO (15.0.4569.1506) 32-bit——中失效。已有四位客户反馈宏无法运行(即API请求未发送),且他们均使用该版本的Excel 2013。我已尝试添加Microsoft XML v6.0和v3.0引用,但均无效。

我计划通过以下代码检测Excel版本,若版本为15.0.4569.1504则使用替代API请求方法,否则使用标准MsXML方法:

If CreateObject("Scripting.FileSystemObject").GetFileVersion(Application.Path & "\WINWORD.exe") = "15.0.4569.1504" Then
' use the alternative api calling method
Else
' use standard Msxml method to call api
End If

想咨询:除Msxml2.ServerXMLHTTP.6.0/3.0外,是否有其他方法可实现HTTP GET请求(简单请求,带URL编码参数且无请求体)并获取响应?

替代解决方案

针对该特定Excel 2013版本,可使用以下几种替代方式实现HTTP GET请求:

1. WinHttp.WinHttpRequest.5.1组件

这是Windows系统广泛支持的HTTP请求组件,逻辑与ServerXMLHTTP一致,兼容性较好:

Dim objRequest As Object
Set objRequest = CreateObject("WinHttp.WinHttpRequest.5.1")

With objRequest
    .Open "GET", "你的API地址(含URL编码参数)", True
    .setRequestHeader "Cache-Control", "no-cache"
    .setRequestHeader "Pragma", "no-cache"
    .Send
    While objRequest.readyState <> 4
        DoEvents
    Wend
    Debug.Print .ResponseText
End With
Set objRequest = Nothing

2. MSXML2.XMLHTTP.6.0组件

这是客户端版本的XMLHTTP组件,与ServerXMLHTTP属于同系列但定位不同,部分环境下兼容性更优:

Dim objRequest As Object
Set objRequest = CreateObject("MSXML2.XMLHTTP.6.0")

With objRequest
    .Open "GET", "你的API地址(含URL编码参数)", True
    .setRequestHeader "Cache-Control", "no-cache"
    .setRequestHeader "Pragma", "no-cache"
    .Send
    While objRequest.readyState <> 4
        DoEvents
    Wend
    Debug.Print .ResponseText
End With
Set objRequest = Nothing

3. InternetExplorer.Application组件(备用方案)

如果前两种方法均失效,可借助IE浏览器组件实现请求(缺点是默认会弹出浏览器窗口,需注意静默处理):

Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")

With ie
    .Visible = False ' 设为True可用于调试
    .Navigate "你的API地址(含URL编码参数)"
    While .Busy Or .ReadyState <> 4
        DoEvents
    Wend
    Debug.Print .Document.Body.InnerText
    .Quit
End With
Set ie = Nothing

版本检测代码优化

当前检测版本使用WINWORD.exe不够准确,建议替换为Excel主程序EXCEL.EXE:

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.GetFileVersion(Application.Path & "\EXCEL.EXE") = "15.0.4569.1504" Then
    ' 执行替代请求方法
Else
    ' 执行标准Msxml请求方法
End If
Set fso = Nothing

内容的提问来源于stack exchange,提问作者kartik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:35:19