In this post we will cover how to integrate ChatGPT into Microsoft Word. ChatGPT can boost your productivity and significantly improve your writing capabilities. Those who don't know ChatGPT, it is a state of the art language model which provides human like responses.
MS Word Macro for ChatGPT
Integrating ChatGPT into MS Word has never been easier with this MS Word Macro for ChatGPT. There are many plugins available in the market but they are paid ones. Here we are covering the open source code to do this for free and customize it according to your needs. There are no prerequisites for using this macro.
Get OpenAI API Key
To get an OpenAI API Key, follow these steps:
- Sign up at platform.openai.com using your Google or Microsoft account.
- Navigate to the
API keys
tab located at the bottom left of the dashboard to access the API key page. - Click
Create new secret key
to generate a new API key.
The OpenAI API comes with charges which are quite affordable. It is based on how much you use the API. If you don't use the API at all during a particular month, you won't be billed for that period. For more details on pricing, refer to OpenAI's pricing page.
Data Privacy : OpenAI's data privacy policy states that user data submitted through their API is not used to train their models.
VBA Code to Run ChatGPT inside MS Word
In this section you will see the VBA code below to run ChatGPT in MS Word. Make sure to enter your API Key in the code highlighted in red.
Sub chatGPT()
Dim request As Object
Dim text As String, response As String, API As String, api_key As String, DisplayText As String, error_result As String
Dim startPos As Long, status_code As Long
Dim prompt As String
Dim selectedText As Range
API = "https://api.openai.com/v1/chat/completions"
'Enter Your API Key
api_key = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
'Model Name
modelName = "gpt-4o-mini"
If api_key = "" Then
MsgBox "Error: API key is blank!"
Exit Sub
End If
' Prompt the user to select text in the document
If Selection.Type <> wdSelectionIP Then
prompt = Trim(Selection.text)
Set selectedText = Selection.Range
Else
MsgBox "Please select some text before running this macro."
Exit Sub
End If
'Cleaning
text = Replace(prompt, Chr(34), Chr(39))
text = Replace(text, vbLf, "")
text = Replace(text, vbCr, "")
text = Replace(text, vbCrLf, "")
' Remove selection
Selection.Collapse
'Create an HTTP request object
Set request = CreateObject("MSXML2.XMLHTTP")
With request
.Open "POST", API, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Bearer " & api_key
.send "{""model"":""" & modelName & """, ""messages"": [{""content"":""" & text & """,""role"":""user""}]," _
& """temperature"": 1}"
status_code = .Status
response = .responseText
End With
'Extract content
If status_code = 200 Then
DisplayText = ExtractContent(response)
'Insert response text into Word document
selectedText.InsertAfter vbNewLine & DisplayText
Else
startPos = InStr(response, """message"": """) + Len("""message"": """)
endPos = InStr(startPos, response, """")
If startPos > Len("""message"": """) And endPos > startPos Then
DisplayText = Mid(response, startPos, endPos - startPos)
Else
DisplayText = ""
End If
'Insert error message into Word document
EDisplayText = "Error : " & DisplayText
selectedText.InsertAfter vbNewLine & EDisplayText
End If
'Clean up the object
Set request = Nothing
End Sub
Function ExtractContent(jsonString As String) As String
Dim startPos As Long
Dim endPos As Long
Dim Content As String
startPos = InStr(jsonString, """content"": """) + Len("""content"": """)
endPos = InStr(startPos, jsonString, "},") - 2
Content = Mid(jsonString, startPos, endPos - startPos)
Content = Trim(Replace(Content, "\""", Chr(34)))
Content = Replace(Content, vbCrLf, "")
Content = Replace(Content, vbLf, "")
Content = Replace(Content, vbCr, "")
Content = Replace(Content, "\n", vbCrLf)
If Right(Content, 1) = """" Then
Content = Left(Content, Len(Content) - 1)
End If
ExtractContent = Content
End Function
Follow the steps below to use ChatGPT in MS Word.
- Open a new or existing MS Word document
- Press Alt+F11 to open the VBA editor.
- Click Insert > Module to create a new module.
- In the module, paste the VBA code.
- Replace API Key in
api_key
with your actual API key. - Close the VBA editor.
- In the MS Word Document, type the text you want to ask ChatGPT
- Select the text you typed in the previous step
- Run the macro by pressing Alt+F8 and then select ChatGPT and hit RUN button.
These modelsgpt-4o
,gpt-4o-mini
,gpt-4-turbo
andgpt-4
always automatically use their respective latest versions.
VBA Code for Formatting ChatGPT Output in Word
The following program returns the output in a presentable form which includes highlighting certain keywords in bold, showing points in bullets or coloring specific sentences.
Sub chatGPTWord()
Dim request As Object
Dim text As String, response As String, API As String, api_key As String, DisplayText As String, error_result As String
Dim startPos As Long, status_code As Long
Dim prompt As String
Dim selectedText As Range
API = "https://api.openai.com/v1/chat/completions"
'Enter Your API Key
api_key = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
'Model Name
modelName = "gpt-4o-mini"
systemPrompt = "You are a helpful chat bot that has expertise in HTML. Do not write explanations on replies. Output should start from <html> and ends with </html>."
If api_key = "" Then
MsgBox "Error: API key is blank!"
Exit Sub
End If
' Prompt the user to select text in the document
If Selection.Type <> wdSelectionIP Then
prompt = Trim(Selection.text)
Set selectedText = Selection.Range
Else
MsgBox "Please select some text before running this macro."
Exit Sub
End If
'Cleaning
text = Replace(prompt, Chr(34), Chr(39))
text = Replace(text, vbLf, "")
text = Replace(text, vbCr, "")
text = Replace(text, vbCrLf, "")
' Remove selection
Selection.Collapse
'Create an HTTP request object
Set request = CreateObject("MSXML2.XMLHTTP")
With request
.Open "POST", API, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Bearer " & api_key
.send "{""model"":""" & modelName & """, ""messages"": [{""content"":""" & systemPrompt & """,""role"":""system""},{" & _
"""content"":""" & text & """,""role"":""user""}],""temperature"": 1}"
status_code = .Status
response = .responseText
End With
'Extract content
If status_code = 200 Then
DisplayText = Replace(response, "\\", "\")
'HTML tags
If InStr(DisplayText, "<html>") <= 0 Then
DisplayText = "<html>" & DisplayText
End If
If InStr(DisplayText, "</html>") <= 0 Then
DisplayText = DisplayText & "</html>"
End If
Dim tags() As Variant
tags = Array("<style>", "<li>", "<p>", "<h1>", "<h2>")
Dim replaceText As String
For Each Tag In tags
If InStr(DisplayText, Tag) > 0 Then
replaceText = ""
Exit For
Else
replaceText = "<br/>"
End If
Next Tag
DisplayText = Replace(DisplayText, vbLf, replaceText)
DisplayText = Replace(DisplayText, vbCr, replaceText)
DisplayText = Replace(DisplayText, vbCrLf, replaceText)
DisplayText = Replace(DisplayText, vbTab, replaceText)
DisplayText = Replace(DisplayText, "\n", replaceText)
CreateHTMLAndConvertToWord (DisplayText)
Else
startPos = InStr(response, """message"": """) + Len("""message"": """)
endPos = InStr(startPos, response, """")
If startPos > Len("""message"": """) And endPos > startPos Then
DisplayText = Mid(response, startPos, endPos - startPos)
Else
DisplayText = ""
End If
'Insert error message into Word document
EDisplayText = "Error : " & DisplayText
selectedText.InsertAfter vbNewLine & EDisplayText
End If
'Clean up the object
Set request = Nothing
End Sub
Function CreateHTMLAndConvertToWord(htmlCode As String)
Dim htmlFile As Object
Dim doc As Document
Dim baseFilePath As String
Dim htmlFilePath As String
Dim outputFilePath As String
Dim app As New Word.Application
Dim currentDate As String
currentDate = Format(Now(), "mm-dd-yyyy_hh-mm-ss")
'Construct full path of HTML file
baseFilePath = ActiveDocument.Path
If ActiveDocument.Path = "" Then
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder to save the file"
If .Show = -1 Then
baseFilePath = .SelectedItems(1)
Else
MsgBox "No folder selected. File will not be saved.", vbExclamation
Exit Function
End If
End With
End If
htmlFilePath = baseFilePath & "\sample_" & currentDate & ".html"
outputFilePath = baseFilePath & "\output_" & currentDate & ".docx"
fileNum = FreeFile
Open htmlFilePath For Output As #fileNum
Print #fileNum, htmlCode
Close #fileNum
'Open HTML file in Word and convert to Word format
Documents.Open FileName:=htmlFilePath, ConfirmConversions:=False, _
ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
'doc.Convert
ActiveDocument.SaveAs2 FileName:=outputFilePath, FileFormat:=wdFormatDocumentDefault
'Close Word document
'doc.Close SaveChanges:=True
'Delete HTML file
Kill htmlFilePath
End Function
Follow the same instructions to use the code as shown in the previous section.
Output will be generated and appeared in a few seconds. It will be saved in a new word document in the same folder where your active word document is stored. File name will be output_mm-dd-yyyy_hr-min-sec.docx
. If your active Word document is not saved in any location, it will prompt you to select the folder where you want to save the output file.
Examples of Using ChatGPT in MS Word
Here are some examples of uses of ChatGPT in MS Word.
You can generate resume with this macro. It is important that you provide a clear and detailed prompt so that ChatGPT generates resume according to your requirements. Always be specific and try with multiple prompts for best outcome. See some of the examples below -
Example 1 :
Write a professional resume for a [Profile Name]. I have [N] years of experience. My past titles and companies were [Title, Company Name]. Include bullet points.
Write a professional resume for a Data Scientist. I have 5 years of experience. My past titles and companies were Analyst, Barclays, Team Lead, JP Morgan. Include bullet points.
Output :
Example 2 :
Write a resume for a [Profile Name] based on this job description. [Add Job Description Here]
You can ask ChatGPT to draft email for you. Whether you need to send a formal business email or a friendly message to a colleague or friend, ChatGPT can help you write a professional and well-drafted message. You just need to provide the purpose of email and some context and ChatGPT will generate a well-written email for you. You can also choose the tone of email.
Write an email to manager about sick leave tomorrow. My Manager’s name is Dave. My name is Deep.
Output :
Write an email to colleague about personal leave tomorrow. My colleague’s name is Joe. My name is Deep. Tone should be informal.
It's also good to specify tone - formal / informal/ humorous.
ChatGPT can be used to summarize lengthy word document for you. For example you have a long document and you are asked to create summary based on it. It may be time consuming and boring to read the whole text and then write summary.
Summarise the text below in bullet points - [PASTE TEXT HERE]
How to Style ChatGPT Output
You can style MS Word Document by adding the following lines to the end of the prompt you ask ChatGPT
- Highlight the headings in dark blue color.
Write a resume for a Software Engineer. Highlight the headings in dark blue color.
- Include bullet points.
- Please format the text to be italic.
- Text should be in red color.
How to Fine Tune ChatGPT Output
In the ChatGPT API, there is a temperature parameter which ranges from 0 to 2. Increasing the value, such as 1.2, will result in a more random output, whereas decreasing the value, like 0.2, will return a more focused output. You can change this in the macro.
Steps for Troubleshooting Errors
1. Error: You exceeded your current quota, please check your plan and billing details
Solution : To fix this issue, you will need to upgrade to a paid account that charges you based on your API usage. This is not ChatGPT Plus but a paid plan for using API. It's very affordable, would roughly cost you less than a dollar per month even when you use API extensively daily.
- Visit OpenAI's website.
- After logged in, go to Billing page, and sign up for "Pay as you go" plan with your debit or credit card. If you are already using this plan, this error indicates that you are sending a high volume of requests to ChatGPT, which it cannot handle. It is also possible that your limit has been set too low. You can check your current quota in your account settings.
2. The error The model: gpt-4 does not exist
means you don't have access to GPT-4 API. You must join the waitlist to access it. Your subscription to ChatGPT Plus (paid version of ChatGPT) does not guarantee automatic access to the GPT-4 API, regardless of whether you have it or not.
3. Sometimes, the ChatGPT API acts strangely and starts producing errors. If the macro was working fine for you before but is now returning errors, I suggest trying again a few more times. If the issue persists, please report it.
ChatGPT Plugin for MS Excel
ChatGPT Plugin for MS PowerPoint.
Share Share Tweet