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

为何VBA中.Send方法返回运行时错误:服务器返回无效/无法识别响应

问题描述

我有一份通过下拉菜单关联数据库(如客户、货币等)获取输入的报表,选择输入后会基于这些输入、已有数据及VBA代码生成报表。执行.send request_str时出现以下运行时错误:

Run-time error '-2147012744 (80072f78)': The server returned an invalid or unrecognized response

对应的VBA代码如下:

Public Sub send_post_request()

    'This function sends the JSON generated by get_inputs by a POST request to the web service hosted on host_url

'    Dim wb As Workbook
'    Dim ws As Worksheet
'    Set wb = ActiveWorkbook
'    Set ws = wb.Sheets("Output")

    'get the JSON to send
    request_str = get_inputs()

'    ws.Range("A1").Value = request_str

    'creates a new HTTP server object
    Dim HTTP_object As Object
    Set HTTP_object = CreateObject("WinHttp.WinHttpRequest.5.1")
    
    With HTTP_object
    
        'set timeout on HTTP response
        .setTimeouts 30000, 30000, 30000, -1
    
        'starts a POST request
        .Open "POST", host_url & tool_url_path, False
    
        'sets headers
        .setRequestHeader "Content-Type", "application/json"
    
        'sends the request
        .send request_str

'        waits for response from server
'        .waitForResponse
'
'        writes server response to worksheet
'        ws.Range("A1").Value = .ResponseText

        'gets the HTTP response status and shows the result of the request
        Status = .StatusText
        If Status = "OK" Then
            msg_text = "Report successfully generated."
            MsgBox msg_text, vbInformation, tool_name
        Else
            msg_text = "Report not generated. Please check your inputs and try again." & vbNewLine & vbNewLine & "If the error persists, please contact: [email]TPICAPCRMSolutions@tpicap.com[/email]"
            MsgBox msg_text, vbExclamation, tool_name
        End If
    
    End With

End Sub

已通过“添加监视”检查输入,一切正常;另有一份输入逻辑、数据来源、请求代码均相似的文件可正常运行。

排查与解决方法
  • 临时启用响应内容输出:取消代码中被注释的.waitForResponse和ws.Range("A1").Value = .ResponseText语句,运行后查看服务器返回的具体内容,哪怕是错误响应,也能定位是格式问题还是服务端逻辑异常。
  • 校验URL拼接结果:对比能正常运行的文件,确认host_url与tool_url_path的拼接结果完全一致,排查是否存在额外空格、特殊字符未转义等问题。
  • 验证JSON格式合法性:将request_str的内容复制到本地JSON校验工具中检查,确认没有引号不匹配、多余逗号等语法错误。
  • 更换HTTP请求组件:尝试把CreateObject("WinHttp.WinHttpRequest.5.1")替换为CreateObject("MSXML2.XMLHTTP.6.0"),不同组件对响应的解析逻辑可能存在差异,换组件测试是否能绕过当前错误。
  • 检查网络与代理设置:确认当前运行环境的网络、代理配置和正常文件的运行环境一致,可临时关闭代理测试请求是否能正常发送。
  • 添加详细错误捕获:在.send语句周围增加错误捕获逻辑,获取更精准的错误信息,示例代码如下:
    On Error Resume Next
    .send request_str
    If Err.Number <> 0 Then
        MsgBox "错误详情: " & Err.Description & " (错误代码: " & Err.Number & ")"
        Err.Clear
        Exit Sub
    End If
    On Error GoTo 0
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:50:37