一、前期准备
1.1 注册并获取 API 密钥
- 访问 DeepSeek 平台:
- 打开浏览器,访问 DeepSeek 官方网站(或您使用的相应平台)。
- 注册并登录您的账户。
- 创建 API 密钥:
- 在用户控制面板中,找到"API Keys"或"API 管理"选项。
- 点击"创建 API Key"按钮,填写应用名称(例如 "Word 文案助手")。
- 系统将生成类似
sk-xxxxxxxxxxxxxxxxxxxx
格式的密钥,请将它复制并妥善保存,后续在 VBA 代码中需要使用此密钥。
二、配置 Word 环境
2.1 启用开发工具选项卡
- 在 Word 中点击【文件】>【选项】。
- 在"Word 选项"对话框中,选择【自定义功能区】。
- 在右侧列表中勾选【开发工具】,然后点击【确定】。
这样在功能区上就会显示"开发工具"选项卡。
2.2 启用宏安全设置
- 在"开发工具"选项卡内,点击【宏安全性】或【信任中心】。
- 进入"信任中心设置",在【宏设置】中选择"启用所有宏"并可勾选"信任对 VBA 工程对象模型的访问"。
注意: 启用宏可能有安全风险,请在受信任的环境下运行。
三、编写 VBA 宏代码
3.1 打开 VBA 编辑器并插入模块
- 在"开发工具"选项卡中点击【Visual Basic】按钮(或使用快捷键 Alt+F11)。
- 在 VBA 编辑器中,右击当前工程(如 "Normal" 或当前文档名称),选择【插入】>【模块】。
建议将此模块命名为 "DeepSeekModule"。
3.2 粘贴下面的完整代码
代码包含两个通用函数用于调用 DeepSeek API 的不同模型(如 deepseek-chat、deepseek-reasoner),以及两个宏分别处理用户选中文本并将结果插入文档。代码中每一部分均有详细注释说明各命令含义。
plain
Option Explicit
'==========================
'【公共 API 调用函数】
'==========================
' 此函数用于向 DeepSeek API 发送请求,参数:
' api_key ------ 您的 API 密钥
' inputText ------ 需要处理的文本(用户选中文本)
' modelName ------ 调用的模型名称,如 "deepseek-chat" 或 "deepseek-reasoner"
' 返回 API 的响应文本(JSON 格式),若出错则返回错误信息。
Private Function CallDeepSeekAPI(api_key As String, inputText As String, modelName As String) As String
Dim API As String
Dim SendTxt As String
Dim Http As Object
Dim status_code As Integer
Dim response As String
' API 请求地址
API = "https://api.deepseek.com/chat/completions"
' 构建请求体(JSON 格式)
' 注:系统角色提示设定为"你是 Word 文案助手"
SendTxt = "{""model"": """ & modelName & """, " & _
"""messages"": [{" & _
"""role"":""system"", ""content"":""你是 Word 文案助手""}," & _
" {""role"":""user"", ""content"":""" & inputText & """}" & _
"], ""stream"": false}"
' 使用 MSXML2.XMLHTTP 对象发送 HTTP 请求
On Error GoTo ErrHandler
Set Http = CreateObject("MSXML2.XMLHTTP")
With Http
.Open "POST", API, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Bearer " & api_key
.Send SendTxt
status_code = .Status
response = .responseText
End With
' 根据响应状态返回结果或错误信息
If status_code = 200 Then
CallDeepSeekAPI = response
Else
CallDeepSeekAPI = "Error: " & status_code & " - " & response
End If
ExitPoint:
Set Http = Nothing
Exit Function
ErrHandler:
CallDeepSeekAPI = "Error: " & Err.Number & " - " & Err.Description
Resume ExitPoint
End Function
'===============================
'【封装具体模型的调用函数】
'===============================
' 调用 deepseek-chat 模型
Function CallDeepSeekChatAPI(api_key As String, inputText As String) As String
CallDeepSeekChatAPI = CallDeepSeekAPI(api_key, inputText, "deepseek-chat")
End Function
' 调用 deepseek-reasoner 模型
Function CallDeepSeekReasonerAPI(api_key As String, inputText As String) As String
CallDeepSeekReasonerAPI = CallDeepSeekAPI(api_key, inputText, "deepseek-reasoner")
End Function
'=====================================
'【主宏:DeepSeek 使用 deepseek-chat 模型】
'=====================================
Sub DeepSeekChat()
Dim api_key As String
Dim inputText As String
Dim response As String
Dim regex As Object
Dim matches As Object
Dim originalSelection As Range
' ============================
'【设置 API 密钥】
' ============================
' 请替换下面的 "在此处替换为您的 API Key" 为您获取的 API 密钥
api_key = "在此处替换为您的 API Key"
' 检查 API 密钥及是否选中有效文本
If api_key = "" Then
MsgBox "Please enter the API key.", vbCritical
Exit Sub
ElseIf Selection.Type <> wdSelectionNormal Then
MsgBox "请选择文本.", vbExclamation
Exit Sub
End If
' ============================
'【保存选中区域】
' ============================
' 保存当前选区,以便后续恢复光标位置
Set originalSelection = Selection.Range.Duplicate
' ============================
'【获取并处理选中文本】
' ============================
inputText = Selection.Text
' 对特殊字符进行转义处理
inputText = Replace(inputText, "\", "\\")
inputText = Replace(inputText, vbCrLf, "")
inputText = Replace(inputText, vbCr, "")
inputText = Replace(inputText, vbLf, "")
inputText = Replace(inputText, Chr(34), "\""")
inputText = Replace(inputText, Chr(39), "\'")
' ============================
'【调用 API 接口】
' ============================
response = CallDeepSeekChatAPI(api_key, inputText)
' 检查返回信息,如果返回 "Error" 开头,则说明调用失败
If Left(response, 5) = "Error" Then
MsgBox response, vbCritical
Exit Sub
End If
' ============================
'【解析 API 返回的 JSON 数据】
' ============================
' 使用正则表达式提取 JSON 中 "content" 字段的值
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = """content"":""(.*?)"""
End With
Set matches = regex.Execute(response)
If matches.Count > 0 Then
response = matches(0).SubMatches(0)
' 将换行符转换成 Word 支持的换行标识
response = Replace(response, "\n", vbCrLf)
' 若有特殊符号,根据需要去除,例如 * 或 #
response = Replace(response, "*", "")
response = Replace(response, "#", "")
' ============================
'【将返回内容插入文档】
' ============================
' 将光标移动到当前选区末尾,插入新段落并输出生成文本
Selection.Collapse Direction:=wdCollapseEnd
Selection.TypeParagraph
Selection.TypeText Text:=response
' 恢复原始选区(可选)
originalSelection.Select
Else
MsgBox "Failed to parse API response.", vbExclamation
End If
End Sub
'=====================================
'【主宏:DeepSeek 使用 deepseek-reasoner 模型】
'=====================================
Sub DeepSeekReasoner()
Dim api_key As String
Dim inputText As String
Dim response As String
Dim regex As Object
Dim matches As Object
Dim originalSelection As Range
' ============================
'【设置 API 密钥】
' ============================
' 请替换下面的 "在此处替换为您的 API Key" 为您的 API 密钥
api_key = "在此处替换为您的 API Key"
' 检查 API 密钥及是否选中有效文本
If api_key = "" Then
MsgBox "Please enter the API key.", vbCritical
Exit Sub
ElseIf Selection.Type <> wdSelectionNormal Then
MsgBox "请选择文本.", vbExclamation
Exit Sub
End If
' ============================
'【保存选中区域】
' ============================
Set originalSelection = Selection.Range.Duplicate
' ============================
'【获取并处理选中文本】
' ============================
inputText = Selection.Text
inputText = Replace(inputText, "\", "\\")
inputText = Replace(inputText, vbCrLf, "")
inputText = Replace(inputText, vbCr, "")
inputText = Replace(inputText, vbLf, "")
inputText = Replace(inputText, Chr(34), "\""")
inputText = Replace(inputText, Chr(39), "\'")
' ============================
'【调用 API 接口】
' ============================
response = CallDeepSeekReasonerAPI(api_key, inputText)
' 检查返回信息,如果返回 "Error" 开头,则说明调用失败
If Left(response, 5) = "Error" Then
MsgBox response, vbCritical
Exit Sub
End If
' ============================
'【解析 API 返回的 JSON 数据】
' ============================
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = """content"":""(.*?)"""
End With
Set matches = regex.Execute(response)
If matches.Count > 0 Then
response = matches(0).SubMatches(0)
response = Replace(response, "\n", vbCrLf)
response = Replace(response, "*", "")
response = Replace(response, "#", "")
' ============================
'【将返回内容插入文档】
' ============================
Selection.Collapse Direction:=wdCollapseEnd
Selection.TypeParagraph
Selection.TypeText Text:=response
' 恢复原选区(可选)
originalSelection.Select
Else
MsgBox "Failed to parse API response.", vbExclamation
End If
End Sub
3.3 保存代码
- 完成粘贴后,保存 VBA 代码,关闭 VBA 编辑器。
四、将宏添加到 Word 自定义功能区(按钮)
为了方便使用,我们可以将写好的宏添加到 Word 的功能区中,具体步骤如下:
- 打开 Word 的"选项"界面:
点击【文件】>【选项】。 - 自定义功能区:
选择【自定义功能区】,在右侧列表中新建一个选项卡(例如命名为 "DeepSeek 助手")或在"开发工具"中添加一个新分组(例如 "DeepSeek 工具")。 - 添加宏命令:
在左侧选择"宏"类别,找到刚才创建的宏(如DeepSeekChat
和DeepSeekReasoner
),将其添加到新建的分组中。你可对按钮名称进行修改,并设置图标以便于识别。 - 点击"确定":
自定义完成后,在功能区中即可看到新添加的按钮,点击即可快速触发相应的宏命令。
五、使用说明与调试
5.1 测试调用 DeepSeek
- 准备测试文本:
- 在 Word 文档中输入一段文本,例如:"请优化下面这段介绍语..."或其他待处理文本。
- 用鼠标选中这段文本。
- 运行宏命令:
- 可以通过"开发工具"选项卡中点击"宏"按钮,选择
DeepSeekChat
(或DeepSeekReasoner
)后点击"运行"。 - 或者直接点击自定义功能区中的按钮执行。
- 可以通过"开发工具"选项卡中点击"宏"按钮,选择
- 查看输出结果:
- 程序会调用 DeepSeek API,对选中文本进行处理(如改写、润色或续写)。
- 处理结果会以新段落的形式插入到选中文本之后,同时原选区可选性恢复。
5.2 错误排查
- API Key 检查:
确保在代码中已替换为您真实的 API 密钥,否则程序会弹出提示要求输入 API Key。 - 网络连接:
确保计算机可以正常访问https://api.deepseek.com
,防火墙或代理设置不影响 HTTP 请求。 - 宏安全设置:
若程序提示"请选择文本"或不能运行宏,请检查当前是否有有效文本选中,以及宏安全设置是否正确配置。
5.3 进阶扩展建议
- 多模型选择:
根据需求,可以增加界面选择不同模型(如"文案助手"与"推理分析")对应的宏,分别调用CallDeepSeekChatAPI
或CallDeepSeekReasonerAPI
。 - JSON 解析优化:
对于复杂返回数据,建议引入 VBA JSON 库(例如 VBA-JSON),提高解析正确率。 - 日志记录:
添加日志记录功能(例如写入文本文件),便于调试和后续维护。
总结
本文详细介绍了如何将 DeepSeek 接入到 Microsoft Word 中的完整流程。通过以下步骤实现:
- API 密钥获取和环境配置:注册 DeepSeek 并获取 API Key;在 Word 中启用开发工具和宏设置。
- VBA 代码编写:将深度处理 API 封装为公共函数,并分别编写调用 deepseek-chat 和 deepseek-reasoner 模型的宏。代码中详细注释了每一步的作用。
- 自定义功能区集成:将编写好的宏添加到 Word 的自定义选项卡中,通过按钮轻松运行。
- 测试与调试:选中待处理文本,运行宏,查看处理结果,针对错误进行排查。
通过此完整教程,您可以轻松将 DeepSeek 的智能功能集成到 Word 文档中,实现高效自动化写作、润色、翻译等功能。如果后续有更多需求或需要改进,您可以基于该基础代码进行进一步扩展和优化。