Gemini API in Excel VBA Macro - Sample Code
In the earlier article we saw how to use Gemini API in Python. But in many offices, Python is not installed & we do not have admin rights to install it. What we always have is Excel.
Good news is, Gemini API can be called from VBA as well. No add-in or extra software is needed.
Imagine you have a list of 200 customer comments in Column A. You want a one line summary or the sentiment (Positive/Negative) for each one in Column B. With this VBA code, you can send each cell to Gemini & get the response written back to the sheet automatically.
Lets see how to do it.
How does VBA talk to Gemini?
Gemini has a REST API. It means, we just have to send a HTTP POST request with our prompt in JSON format & the API sends back the answer, again in JSON format.
In VBA, this can be done with the object "MSXML2.ServerXMLHTTP". This is the same object we used to extract data from website to Excel. Only difference is, instead of GET we use POST & send some data along with it.
Before starting, get your free API key from Google AI Studio. Login with your Google account & click "Create API key". Steps are explained in detail here: How to Get Free Gemini API Key.
VBA Code to Send Prompt to Gemini & Get Response
Follow these steps.
- Open a new Excel workbook & save it as .xlsm (macro enabled) file.
- Press Alt + F11 to open VB editor.
- Go to Insert -> Module.
- Copy paste the below code in the module.
- Paste your API key in the line GEMINI_API_KEY.
- Type a question in cell A1 of first sheet.
- Place the cursor inside Ask_Gemini_From_Excel & press F5.
The answer from Gemini will be written in cell B1.
Option Explicit
'Get your API Key from https://aistudio.google.com/apikey
'Leave it empty to read it from GEMINI_API_KEY environment variable
Private Const GEMINI_API_KEY As String = "PASTE_YOUR_API_KEY_HERE"
'Gemini model to use. Change this when Google releases a newer model.
Private Const GEMINI_MODEL As String = "gemini-3.8-flash"
Sub Ask_Gemini_From_Excel()
Dim sPrompt As String
Dim sReply As String
'Read the question from cell A1
sPrompt = ThisWorkbook.Sheets(1).Range("A1").Value
If Trim(sPrompt) = "" Then
MsgBox "Type your question in cell A1 & run again"
Exit Sub
End If
'Send to Gemini & write the answer in cell B1
sReply = Gemini_Get_Response(sPrompt)
ThisWorkbook.Sheets(1).Range("B1").Value = sReply
MsgBox "Gemini Response Received"
End Sub
Function Gemini_Get_Response(ByVal sPrompt As String) As String
Dim oHTTP As Object
Dim sURL As String, sBody As String, sApiKey As String
'Use the key from constant, else from environment variable
sApiKey = GEMINI_API_KEY
If sApiKey = "" Then sApiKey = Environ("GEMINI_API_KEY")
sURL = "https://generativelanguage.googleapis.com/v1beta/models/" & GEMINI_MODEL & ":generateContent"
'Build the JSON request body: {"contents":[{"parts":[{"text":"prompt"}]}]}
sBody = "{""contents"":[{""parts"":[{""text"":""" & Json_Escape(sPrompt) & """}]}]}"
'Send HTTP POST request to Gemini API
Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
oHTTP.setTimeouts 10000, 10000, 60000, 120000
oHTTP.Open "POST", sURL, False
oHTTP.setRequestHeader "Content-Type", "application/json"
oHTTP.setRequestHeader "x-goog-api-key", sApiKey
oHTTP.send sBody
'Check Return Code from API Server & Proceed
If oHTTP.Status <> 200 Then
Gemini_Get_Response = "Error " & oHTTP.Status & ": " & oHTTP.responseText
Else
Gemini_Get_Response = Json_Get_Text(oHTTP.responseText)
End If
Set oHTTP = Nothing
End Function
'Escape special characters in the prompt, so that JSON does not break
Private Function Json_Escape(ByVal sText As String) As String
Dim i As Long, ch As String, sOut As String
For i = 1 To Len(sText)
ch = Mid$(sText, i, 1)
Select Case ch
Case "\": sOut = sOut & "\\"
Case """": sOut = sOut & "\"""
Case vbCr: sOut = sOut & "\r"
Case vbLf: sOut = sOut & "\n"
Case vbTab: sOut = sOut & "\t"
Case Else
If AscW(ch) >= 0 And AscW(ch) < 32 Then
sOut = sOut & "\u" & Right$("000" & Hex(AscW(ch)), 4)
Else
sOut = sOut & ch
End If
End Select
Next i
Json_Escape = sOut
End Function
'Read all "text" values from the Gemini JSON response
Private Function Json_Get_Text(ByVal sJson As String) As String
Dim pos As Long, i As Long
Dim ch As String, sPart As String, sOut As String
pos = InStr(1, sJson, """text""", vbBinaryCompare)
Do While pos > 0
'Move to the colon & then to the opening quote of the value
i = InStr(pos + 6, sJson, ":")
i = InStr(i + 1, sJson, """") + 1
sPart = ""
Do While i <= Len(sJson)
ch = Mid$(sJson, i, 1)
If ch = "\" Then
i = i + 1
Select Case Mid$(sJson, i, 1)
Case "n": sPart = sPart & vbLf
Case "r": sPart = sPart & vbCr
Case "t": sPart = sPart & vbTab
Case "b", "f": 'ignore these
Case "u"
sPart = sPart & ChrW(CLng("&H" & Mid$(sJson, i + 1, 4)))
i = i + 4
Case Else
sPart = sPart & Mid$(sJson, i, 1)
End Select
ElseIf ch = """" Then
Exit Do
Else
sPart = sPart & ch
End If
i = i + 1
Loop
sOut = sOut & sPart
pos = InStr(i, sJson, """text""", vbBinaryCompare)
Loop
If sOut = "" Then sOut = "No text found in response: " & sJson
Json_Get_Text = sOut
End Function
What does this code do?
The main function is Gemini_Get_Response. It takes the prompt text, sends it to Gemini & returns the answer as a string. So, you can call it from any other macro of yours.
The other 2 functions are helpers.
- Json_Escape: If the prompt has double quotes or new lines (for example, text copied from an email), the JSON will break & Gemini will return Error 400. This function takes care of it.
- Json_Get_Text: The response from Gemini is a JSON text. The answer is inside candidates -> content -> parts -> text. This function picks only the "text" values & converts \n into proper line breaks.
I have written a simple parser here, so that the code works without any reference or extra module. If you are already using JsonConverter.bas in your project, you can use ParseJson instead. It is explained in this JSON parser VBA article.
Send Prompts for All Rows in Excel Sheet
Now the useful part. Add this macro to the same module. It reads every row from Column A (from row 2) & writes the Gemini response in Column B.
Sub Ask_Gemini_For_All_Rows()
Dim ws As Worksheet
Dim lastRow As Long, i As Long
Set ws = ThisWorkbook.Sheets(1)
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
'Process only rows that have a prompt & no response yet
If Trim(ws.Cells(i, 1).Value) <> "" And ws.Cells(i, 2).Value = "" Then
ws.Cells(i, 2).Value = Gemini_Get_Response(ws.Cells(i, 1).Value)
Application.StatusBar = "Gemini: Processed row " & i & " of " & lastRow
'Small wait to stay within API rate limit
Application.Wait Now + TimeValue("00:00:02")
DoEvents
End If
Next i
Application.StatusBar = False
MsgBox "All rows processed"
End Sub
Since it skips rows that already have a response, you can stop the macro in between & run it again later. It will continue from where it stopped.
Tip: Write the instruction along with the data. For example, if Column A has customer comments, then send "Classify this comment as Positive, Negative or Neutral. Reply with one word only: " & ws.Cells(i, 1).Value. Then Column B will have clean one word answers, which you can use in a Pivot table.
Things to Know Before Using This
- Do not share the workbook with API key in it: The key is stored in plain text inside the VBA code. If you are going to share the file, leave GEMINI_API_KEY empty & set it as an environment variable in your own computer (setx GEMINI_API_KEY "your-key" in command prompt & restart Excel).
- Do not make it as a worksheet formula: It is tempting to create a function like =GEMINI(A1). But Excel recalculates formulas very often & each recalculation will send a new request. Your free quota will be over in minutes. Use a macro with a button instead.
- Response has ** and # symbols: Gemini replies in Markdown format by default. Add "Reply in plain text, without markdown" at the end of your prompt.
- Error 404: Model name is wrong or retired. Check the latest model name in Google AI Studio & change GEMINI_MODEL.
- Error 429: Too many requests. Increase the wait time in the loop.
- Windows only: MSXML2 object is not available in Excel for Mac. This code works in Excel 2010 & above on Windows, both 32 bit & 64 bit.
If you use Outlook, the same functions can summarize your emails with Gemini.
With this, Excel becomes a simple AI tool for bulk work like summarizing, translating, classifying or cleaning text data. The same code will work in Word, Outlook or Access VBA also, since it does not use anything specific to Excel other than reading & writing the cells.