步骤3:设置VB模块
步骤3:设置VB模块
选择【开发工具】

选择【VB编辑器】

Normal选项下,插入-模块:

这里以添加阿里云百练的千问2.5大模型为例:
1Function CallDeepSeekAPI(api_key As String, inputText As String) As String
2Dim API As String
| 3 | DimSendTxtAsString |
|---|---|
| 4 | DimHttpAsObject |
| 5 | Dimstatus_codeAsInteger |
"https://dashscope.aliyuncs.com/compatib le-mode/v1/chat/completions"
9SendTxt = "{""model"": ""qwen-max- 0125"", ""messages"":
[{""role"":""system"", ""content"":""请根据用户的问题给出详细的解答。""},
{""role"":""user"", ""content"":""" & inputText & """}]}"
10 11Set Http =
CreateObject("MSXML2.XMLHTTP")
12With Http 13.Open "POST", API, False
14.setRequestHeader "Content- Type", "application/json"
15.setRequestHeader "Authorization", "Bearer " & api_key
16.send SendTxt
| 17 | status_code=.Status |
|---|---|
| 18 | response=.responseText |
| 19 | EndWith |
20 21' 弹出窗口显示 API 响应(调试用)
22' MsgBox "API Response: " & response, vbInformation, "Debug Info"
23
| 24 | Ifstatus_code=200Then |
|---|---|
| 25 | CallDeepSeekAPI=response |
| 26 | Else |
| 27 | CallDeepSeekAPI="Error:"& |
status_code & " - " & response
31End Function 32
33Sub qwen2_5()
| 34 | Dimapi_keyAsString |
|---|---|
| 35 | DiminputTextAsString |
| 36 | DimresponseAsString |
| 37 | DimregexAsObject |
| 38 | DimmatchesAsObject |
| 39 | DimoriginalSelectionAsObject |
40 41
42api_key = "填写你自己的API-KEY"'填写你自己的API-KEY
43If api_key = "" Then 44MsgBox "Please enter the API
key."
45Exit Sub 46ElseIf Selection.Type <>
wdSelectionNormal Then
| 47 | MsgBox"Pleaseselecttext." |
|---|---|
| 48 | ExitSub |
| 49 | EndIf |
50 51' 保存原始选中的文本
52Set originalSelection = Selection.Range.Duplicate
53 54inputText =
Replace(Replace(Replace(Replace(Replace( Selection.Text, "\", "\\"), vbCrLf, ""),
vbCr, ""), vbLf, ""), Chr(34), "\""")
56 57If Left(response, 5) <> "Error" Then
58Set regex = CreateObject("VBScript.RegExp")
59With regex
| 60 | .Global=True |
|---|---|
| 61 | .MultiLine=True |
| 62 | .IgnoreCase=False |
| 63 | .Pattern="""content"":"" |
(.*?)"""
64End With 65Set matches =
regex.Execute(response)
66If matches.Count > 0 Then 67response =
matches(0).SubMatches(0)
68' 处理换行符和特殊字符 69response = Replace(response,
"\n\n", vbNewLine)' 双换行替换为真实的单换行
70response = Replace(response, "\n", vbNewLine)' 单换行替换为真实的换行
71response = Replace(Replace(response, """",
Chr(34)), """", Chr(34))
72 73' 取消选中原始文本
74Selection.Collapse Direction:=wdCollapseEnd
76' 将内容插入到选中文字的下一行
78Selection.TypeText Text:=response
79
| 80 | '将光标移回原来选中文本的末尾 |
|---|---|
| 81 | originalSelection.Select |
| 82 | Else |
| 83 | MsgBox"FailedtoparseAPI |
response.", vbExclamation 84End If
85Else 86MsgBox response, vbCritical
87End If 88End Sub
89
API-KEY需要从如下网址获取:https://bailian.console.aliyun.co m/
注意:在获取key之前,需要注册、并完成个人实名认证。
