OpenAI API VBA function returns #Value! but MsgBox displays response

题意:"OpenAI API VBA 函数返回 #Value!,但 MsgBox 显示响应"

问题背景:

I am trying to integrate the OpenAI API into Excel. The http request to OpenAI chat completion works correctly and the response is OK. When I display it with a MsgBox, it looks fine.

"我正在尝试将 OpenAI API 集成到 Excel 中。对 OpenAI 聊天完成的 HTTP 请求正常工作,响应也正常。当我使用 MsgBox 显示它时,它看起来很好。"

But when the function is called in a sheet, the returned value is #VALUE!

"但当在工作表中调用该函数时,返回的值是 #VALUE!"

python 复制代码
Public Function GPT(InputPrompt) As String
  'Define variables
  Dim request As Object
  Dim text, response, API, api_key, DisplayText, GPTModel As String
  Dim GPTTemp As Double
  Dim startPos As Long
  Dim rng As Range
  Dim httpRequest As Object
  Dim countArray As Variant

 
  'API Info
  API = "https://api.openai.com/v1/chat/completions"
  api_key = Trim(Range("API_Key").value)
  'Note: for future upgrades, please replace with GPT-4 etc
  GPTModel = Range("Model_Number").value
  
  If api_key = "" Then 'API key is missing!
    MsgBox "Error: API cannot be blank! Please go to 'Configuration' tab and enter a valid OpenAI API key", vbExclamation, "GPT for Excel"
    frmStatus.Hide
    Exit Function
  End If
    
  'Clean input text and make JSON safe
  text = CleanInput(InputPrompt)
  
  'Create request object
  Set httpRequest = CreateObject("MSXML2.XMLHTTP")
  'Set httpRequest = New MSXML2.XMLHTTP60
  
  'Get temp from Config panel
  GPTTemp = Range("GPT_temperature").value
  
  'Assemble request body
  Dim requestBody As String
  requestBody = "{""model"": ""gpt-4"", ""messages"": [{""role"": ""user"", ""content"": """ & text & """}], ""temperature"": 0.7}"

  With httpRequest
     .Open "POST", API, False
     .setRequestHeader "Content-Type", "application/json"
     .setRequestHeader "Authorization", "Bearer " & api_key
     .send (requestBody)
  End With

  If httpRequest.Status = 200 Then 'Successfully called OpenAI API
   response = httpRequest.responseText
   'Get usage info from response object
   countArr = ExtractUsageInfo(response)
    
   startPos = InStr(response, """content"":") + Len("""content"":") + 2
   endPos = InStr(startPos, response, "},")
   DisplayText = Trim(Mid(response, startPos, endPos - startPos))
   DisplayText = Mid(DisplayText, 1, Len(DisplayText) - 2)
   DisplayText = CleanOutput(DisplayText)
    
   Set request = Nothing
   If FillActive = False Then frmStatus.Hide
   MsgBox (GPT)
   GPT = DisplayText
   MsgBox (GPT)
   If Range("Log_Data").value = "Yes" Then
    Call UpdateLogFile(countArr)
   End If
  Exit Function

End Function

问题解决:

You are limited as to what you can do in a custom worksheet function. While I can't find an explicit reference to making web or API calls in the MS Docs my experience of worksheet functions leads me to not be surprised that this doesn't work.

"在自定义工作表函数中,你的操作是有限的。虽然我在微软文档中找不到明确提到进行 Web 或 API 调用的内容,但根据我对工作表函数的经验,这种方法不起作用并不令人意外。"

An alternative would be to add a Button or Shape to your worksheet then associated that button with a Sub such as

"另一种方法是在你的工作表中添加一个按钮或形状,然后将该按钮与一个 `Sub` 关联,例如:"

python 复制代码
Sub ButtonClicked()
    Dim Response As String, InputPrompt As String
    InputPrompt = CStr(ThisWorkbook.Sheets("Sheet1").Range("A1").Value)
    Response = GPT(InputPrompt)
    ThisWorkbook.Sheets("Sheet1").Range("A2").Value = Response
End Sub

Which uses your existing GPT function to get a response for the text in cell A1 and loads it into cell A2 (both in 'Sheet1' in this case ... obviously you can change the cells and worksheet as needed).

"这个方法使用你现有的 `GPT` 函数来获取单元格 A1 中的文本的响应,并将其加载到单元格 A2 中(在本例中,这两个单元格都在 'Sheet1' 中......显然,你可以根据需要更改单元格和工作表)。"

相关推荐
Hello_Damon_Nikola1 小时前
Ollama 终极使用指南
ai·ai编程
AI英德西牛仔2 小时前
豆包导出 pdf 颜色不一样怎么办,选用 AI 导出鸭优化文档导出,结合行业白皮书数据解析色彩失真成因
人工智能·ai·chatgpt·pdf·deepseek·ai导出鸭
xcLeigh4 小时前
AI内容检测:如何判断一篇文章是否为AI生成
人工智能·ai·提示词·灵感写作
全栈技术负责人4 小时前
解密 MCP(Model Context Protocol):大模型时代的“Type-C”总线与三驾马车架构深度解析
开发语言·ai·架构
yonlin4 小时前
【解决方案】Codex Cli 复制多行提示词到输入框,可能截断提示词,导致提示词不完整的解决方案
ai·codex
安逸sgr5 小时前
循环神经网络 RNN、LSTM、GRU 是什么?为什么能处理序列?
人工智能·ai·大模型·agent·智能体
猿小猴子5 小时前
主流 AGENT 实战教程「OpenCodex」与「ChatGPT Work」与「Codex Record & Replay」介绍
人工智能·ai·chatgpt·codex·minimax·deepseek·opencodex
TechEdu2026065 小时前
[人工智能]RLlib:基于Ray的可扩展强化学习框架
人工智能·ai
sbjdhjd7 小时前
企业站 SQL 注入实战:PCRE 正则回溯绕过关键词 WAF 完整实战 | 进阶02
sql·安全·web安全·网络安全·ai·开源·php
安逸sgr7 小时前
卷积神经网络 CNN 是什么?为什么适合处理图像?
人工智能·ai·大模型·agent·智能体