Excel中,创建一个公式来调用ChatGPT API并返回结果
作者:weixin02 · 2025-09-06 · 阅读时间:4分钟
在Office 365的Excel中,虽然有了Copilot,目前我们还无法使用。不过可以用自定义Formula来调用ChatGPT来实现。本文是演示使用VBA创建一个自定义函数 AI()调用OpenAI API,并返回API的响应。
步骤1:启用开发工具
- 打开Excel,点击“文件” > “选项”。
- 选择“自定义功能区”,然后在右侧勾选“开发工具”选项。
- 点击“确定”启用开发工具。
步骤2:创建VBA脚本
- 在Excel中,点击“开发工具”选项卡,然后点击“Visual Basic”。
- 在VBA编辑器中,点击“插入” > “模块”,插入一个新模块。
- 将以下代码粘贴到Module1中:
'================================================
' Created by ChatGPT-4o on 2024-08-24.
' Modified by Vincent Meng.
'================================================
Function AI(arg As String) As String
Dim apiKey As String
Dim url As String
Dim http As Object
Dim jsonBody As String
Dim response As String
Dim startPos As Long
Dim endPos As Long
On Error GoTo ErrorHandler ' Enable error handling
' Your OpenAI API key
apiKey = "XXXXX" ' Replace it with your actual OpenAI API Key
' OpenAI API endpoint for chat completion
url = "https://api.openai.com/v1/chat/completions"
' Create the JSON body for the API request
jsonBody = "{""model"": ""gpt-4o-mini"", ""messages"": [{""role"": ""user"", ""content"": """ & arg & """}], ""max_tokens"": 1000}"
' Create HTTP object
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
With http
.Open "POST", url, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Bearer " & apiKey
On Error GoTo HTTPErrorHandler ' Enable error handling for HTTP request
.send jsonBody
response = .responseText
On Error GoTo 0 ' Disable error handling for HTTP request
End With
' Simple string parsing: Find the "content" field and extract its value
startPos = InStr(response, """content"": """) + Len("""content"": """)
If startPos > 0 Then
endPos = InStr(startPos, response, """")
If endPos > startPos Then
AI = Replace(Mid(response, startPos, endPos - startPos), "\n", vbCrLf)
Else
AI = "Error: Could not parse the response."
End If
Else
AI = "Error: 'content' field not found in the response."
End If
Exit Function
ErrorHandler:
AI = "Error: " & Err.Description ' Catch general errors and return error message
Exit Function
HTTPErrorHandler:
AI = "HTTP Error: Unable to connect to the API."
Exit Function
End Function
步骤3:使用自定义函数
- 回到Excel工作表。
- 在单元格中输入公式
=AI(A1)
(假设A1
单元格中包含你要发送给ChatGPT的文本)。 - 按
Enter
键,VBA脚本将调用API并返回结果。

通过上述步骤,你可以在Excel中创建一个自定义的 AI()
函数,用来调用ChatGPT的API,并将结果直接返回到Excel单元格中。
▶注意事项
- API Key:确保将
XXXXX
替换为你自己的ChatGPT API Key。 - API请求限制:注意OpenAI的API调用限制和费用,避免超过配额。
- 网络连接:此函数依赖国外网络连接,不能科学上网的话函数将无法正常工作。
▶安全提示
将API Key嵌入VBA代码中时,请注意安全性,避免泄露敏感信息。如果是多人共享的Excel文件,建议使用更安全的方式存储API Key。
文章转自微信公众号@SAPHANA
热门推荐
一个账号试用1000+ API
助力AI无缝链接物理世界 · 无需多次注册
3000+提示词助力AI大模型
和专业工程师共享工作效率翻倍的秘密
热门API
- 1. AI文本生成
- 2. AI图片生成_文生图
- 3. AI图片生成_图生图
- 4. AI图像编辑
- 5. AI视频生成_文生视频
- 6. AI视频生成_图生视频
- 7. AI语音合成_文生语音
- 8. AI文本生成(中国)
最新文章
- Python 使用 话费 API:轻松实现自动话费查询功能
- 构建现代RESTful API:C#中的关键标准和最佳实践
- 优化 ASP.NET Core Web API 性能方法
- 如何设计一个对外的安全接口?
- 2025 LangGraph AI 工作流引擎|可视化多 Agent 协作+节点扩展教程
- 动漫百科全书API:你准备好探索动漫世界的无限可能了吗?
- Claude API在中国停用后的迁移与替代方案详解
- Grafana API 入门指南:自动化仪表板管理与高级功能
- 常用的14条API文档编写基本准则
- 如何获取 Kimi K2 API 密钥(分步指南)
- 为什么需要隐藏您的 API Key 密钥
- 盘点Python网页开发轻量级框架Flask知识