代码参考up主小卫是David
使用效果,API请求异常后,返回报错提醒
Sub chatGPT()
'
' chatGPT 宏
'
'
Dim selectedText As String
Dim apiKey As String
Dim response As Object, re As String
Dim midString As String
Dim ans As String
On Error GoTo ErrorHandler
If Selection.Type = wdSelectionNormal Then
selectedText = Selection.Text
selectedText = Replace(selectedText, ChrW$(13), "")
apiKey = "your_api_key"
URL = "https://api.openai.com/v1/chat/completions"
Set response = CreateObject("MSXML2.XMLHTTP")
response.Open "POST", URL, False
response.setRequestHeader "Content-Type", "application/json"
response.setRequestHeader "Authorization", "Bearer " + apiKey
response.Send "{""model"":""gpt-3.5-turbo"", ""messages"":[{""role"":""user"",""content"":""" & selectedText & """}],""temperature"":0.7}"
If response.Status = 200 And Len(response.responseText) > 0 Then
re = response.responseText
midString = Mid(re, InStr(re, """content"":""") + 11)
ans = Split(midString, """")(0)
ans = Replace(ans, "\n", "")
Selection.Text = selectedText & vbNewLine & ans
Else
MsgBox "请求失败,响应内容为:" & vbNewLine & response.responseText, vbExclamation, "请求失败"
End If
Else
Exit Sub
End If
Exit Sub
ErrorHandler:
MsgBox "发生错误:" & Err.Description, vbCritical, "运行时错误"
End Sub
爱画画的Pary 2023-08-15