Connecting a Local LLM to Excel with VBA
This article walks you through connecting a locally deployed large language model to Microsoft Excel using VBA and Ollama. You will set up an Ollama inference service, download a quantized Qwen 2.5 model, and build a workbook where users type a question in a cell, click a button, and receive the model's answer in the spreadsheet. The solution uses synchronous, non-streaming HTTP requests and includes complete, commented VBA code for JSON construction, response parsing, and error handling, along with guidance on environment setup, performance tuning, data privacy, and troubleshooting.
1. Why Connect a Local Model to Excel
Locally deployed LLMs often remain stuck in the command line. The model can answer questions, but business users spend their day in Excel, Word, and similar office tools. By bringing the model’s capabilities into a spreadsheet, users simply type a question into a cell, click a button, and get an answer—no window switching, no new tools to learn.
The scope of this article: Windows with Excel 2016 or later, Ollama as the inference service, and VBA on the Excel side sending synchronous, non-streaming HTTP requests. Streaming output, knowledge base retrieval, and multi-user concurrency are out of scope, but they can be built on top of this foundation.
2. Overall Architecture
The solution has three layers, each with a distinct responsibility and a clear replacement point.
| Layer | Responsibility | Replacement Point |
|---|---|---|
| Presentation | Excel worksheet: question in A2, status in B2, answer in A4, errors in A6 | Can be swapped for Word or another UI |
| Bridge | VBA builds the JSON payload, sends the HTTP request, and parses the response | Only this layer changes if you switch language or interface |
| Service | Ollama’s /api/chat endpoint, which loads the model and generates text | Can be replaced by any compatible endpoint, though the data boundary shifts accordingly |
This layering lets each piece be adjusted independently. For example, replacing the service layer with a cloud API only requires changing the bridge layer’s URL and authentication method.
3. Environment Setup
3.1 Install Ollama
Download the Windows installer from the official Ollama website, or run the following in PowerShell:
winget install Ollama.Ollama
After installation, open a new terminal and run ollama --version to confirm it works.
3.2 Download a Model and Verify the Service
Download the 7B-parameter Qwen model:
ollama pull qwen2.5:7b
The default version is 4-bit quantized, with a download size of roughly 4.7GB. If your hardware allows, you can choose the 14B version (qwen2.5:14b), about 9GB, which typically produces better answers.
Reference minimums for memory or VRAM—verify actual usage with Task Manager and ollama ps: the 7B model needs at least 8GB of available memory or VRAM, and the 14B model needs 12GB or more. If VRAM is insufficient, the model partially runs on CPU and slows down noticeably.
Check that the API responds correctly:
curl http://127.0.0.1:11434/api/chat -d "{\"model\":\"qwen2.5:7b\",\"stream\":false,\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}"
If the returned JSON contains a message field with reply text, the service is working. Ollama listens only on 127.0.0.1 port 11434 by default. If you change OLLAMA_HOST to 0.0.0.0 via an environment variable, other machines on the LAN can reach the service—so only do this if necessary, and pair it with firewall rules restricting sources.
3.3 Configure Excel and Macros
Confirm your Excel version is 2016 or later. Enable the Developer tab under “File > Options > Customize Ribbon.” Save the file as an “Excel Macro-Enabled Workbook (.xlsm).”
4. Implementation
4.1 Design the Worksheet
Set up the following areas in the worksheet:
- A2: user input for the question; merge several cells if needed for readability.
- B2: status indicator, such as “Requesting,” “Done,” or “Failed.”
- A4: displays the model’s answer.
- A6: displays error messages for troubleshooting.
Insert a button on the worksheet and assign it to the CallLocalModel macro below.
4.2 Writing the Non-Streaming Call Code
Open the VBA editor (Alt+F11), insert a standard module under the workbook object, and paste the following code. The worksheet name defaults to Sheet1; adjust it if yours differs.
Option ExplicitConst LLM_ENDPOINT As String = "http://127.0.0.1:11434/api/chat"Const LLM_MODEL As String = "qwen2.5:7b"Sub CallLocalModel()Dim ws As WorksheetDim question As String, body As String, resp As StringDim http As ObjectDim answer As StringDim token As StringSet ws = ThisWorkbook.Worksheets("Sheet1")question = Trim(CStr(ws.Range("A2").Value))ws.Range("A6").ClearContentsIf question = "" ThenMsgBox "Please enter a question in cell A2.", vbExclamationExit SubEnd Ifbody = "{""model"":""" & LLM_MODEL & """," & _"""stream"":false," & _"""options"":{""temperature"":0.7,""num_predict"":512}," & _"""messages"":[{""role"":""user"",""content"":""" & JsonEscape(question) & """}]}"On Error GoTo ErrHandlerSet http = CreateObject("MSXML2.ServerXMLHTTP.6.0")http.setTimeouts 5000, 5000, 10000, 180000http.Open "POST", LLM_ENDPOINT, Falsehttp.setRequestHeader "Content-Type", "application/json; charset=utf-8"token = Environ("LOCAL_LLM_TOKEN")If token <> "" Then http.setRequestHeader "Authorization", "Bearer " & tokenws.Range("B2").Value = "Requesting"Application.Cursor = xlWaithttp.send bodyApplication.Cursor = xlDefaultIf http.Status <> 200 ThenErr.Raise vbObjectError + 1, , "HTTP " & http.Status & " " & http.statusTextEnd Ifresp = http.responseTextanswer = ExtractContent(resp)If answer = "" Then Err.Raise vbObjectError + 2, , "content field not found in response"' Prefix with a single quote so an answer starting with "=" is not treated as a formulaws.Range("A4").Value = "'" & answerws.Range("B2").Value = "Done"Exit SubErrHandler:Application.Cursor = xlDefaultws.Range("B2").Value = "Failed"ws.Range("A6").Value = "Error: " & Err.DescriptionEnd SubFunction JsonEscape(ByVal s As String) As Strings = Replace(s, "\", "\\")s = Replace(s, """", "\""")s = Replace(s, vbCrLf, "\n")s = Replace(s, vbLf, "\n")s = Replace(s, vbCr, "\n")s = Replace(s, vbTab, "\t")JsonEscape = sEnd FunctionFunction ExtractContent(ByVal json As String) As StringDim key As String, p As Long, i As Long, ch As String, raw As Stringkey = """content"":"""p = InStr(1, json, key)If p = 0 Then Exit Functioni = p + Len(key)Do While i <= Len(json)ch = Mid$(json, i, 1)If ch = "\" Thenraw = raw & Mid$(json, i, 2)i = i + 2ElseIf ch = """" ThenExit DoElseraw = raw & chi = i + 1End IfLoopExtractContent = JsonUnescape(raw)End FunctionFunction JsonUnescape(ByVal s As String) As StringDim out As String, i As Long, nxt As Stringi = 1Do While i <= Len(s)If Mid$(s, i, 1) = "\" And i < Len(s) Thennxt = Mid$(s, i + 1, 1)Select Case nxtCase "n": out = out & vbLfCase "r": out = out & vbCrCase "t": out = out & vbTabCase "u"out = out & ChrW(CLng("&H" & Mid$(s, i + 2, 4)))i = i + 4Case "b", "f"' Ignore backspace and form feedCase Elseout = out & nxtEnd Selecti = i + 2Elseout = out & Mid$(s, i, 1)i = i + 1End IfLoopJsonUnescape = outEnd Function
What each part does:
LLM_ENDPOINTandLLM_MODELcentralize the service URL and model name; when redeploying, you only change these two lines.JsonEscapehandles quotes, backslashes, and line breaks in the question text. Without escaping, a user input containing quotes would make the request body invalid JSON, and the server would return a 400 error.- The
ServerXMLHTTPobject sends a synchronous request.setTimeoutssets the resolve, connect, send, and receive timeouts in milliseconds; increase the receive timeout if the model generates long content. Environ("LOCAL_LLM_TOKEN")reads a token from a system environment variable. Ollama needs no token by default—only set this if you’ve added a reverse proxy with authentication. Never hardcode tokens in code or in the workbook.ExtractContentpulls out themessage.contentfield. In Ollama’s non-streaming response, the first occurrence of"content":"marks the start of the model’s reply, so a direct search is sufficient.
4.3 How Response Parsing Works
When stream is false, Ollama returns a complete JSON object structured like this:
{"model":"qwen2.5:7b","message":{"role":"assistant","content":"...reply text..."},"done":true,"total_duration":…,"eval_count":…,"eval_duration":…}
ExtractContent scans the string character by character, stopping at the first unescaped quote, and JsonUnescape then restores escape sequences such as \n, \", and \uXXXX. Chinese text is usually returned as-is, but in some environments it appears as \uXXXX, so the parser must handle that form.
This hand-rolled parsing approach suits responses with a fixed structure. If you later need to parse more complex structures, use a mature JSON library, or call JScript’s JSON.parse via ScriptControl—note that ScriptControl may be unavailable in 64-bit Office, so verify it first.
One caveat: Ollama’s default streaming output is line-delimited JSON (NDJSON), not SSE. The code in this article only handles non-streaming responses, so this issue doesn’t arise here.
4.4 Triggering the Macro
Use only the button to trigger the macro—do not call it from a Worksheet_Change event. Every edit to A2 would fire the event, and users working in the sheet would easily send accidental requests, tying up model resources.
Excel’s UI briefly freezes during the synchronous request; that’s inherent to synchronous calls. If you need a non-blocking UI, you can switch to WinHttp.WinHttpRequest.5.1 with async callbacks, but code complexity increases significantly—that’s beyond this article’s scope.
5. Usage and Verification
Type a question in A2—for example, “Summarize the following sales data in three sentences”—paste the data into the area below A2, and click the button. B2 shows “Requesting,” then “Done,” and A4 displays the model’s answer.
Typical use cases for this setup:
- Data interpretation: given statistical figures, have the model produce a business explanation.
- Text drafting: supply a topic and key points, and have the model generate paragraphs.
- Content cleanup: paste meeting notes and have the model extract action items.
For verification, run a set of fixed questions as a baseline and check whether the output is complete and special characters display correctly. If answers come back empty or garbled, first review the parsing functions and the charset in the request headers from Chapter 4.
6. Data Privacy and Macro Security
“Data never leaves the machine” is a key advantage of this approach—but it’s conditional. Data stays local or on your intranet only when all of the following hold: the inference service listens only on localhost, the model comes from a trusted source, Excel connects to no external services, and logs and caches are stored in controlled locations. If you use a cloud model or expose the port beyond your LAN, that data boundary no longer applies.
When handling sensitive data such as customer records, financial data, or medical records, also keep these points in mind:
- Mask fields such as ID numbers and phone numbers before sending input.
- Ollama’s service logs may record request content; clean them up regularly and restrict access to the log directory.
- Only enable macros from trusted sources. Keep macros disabled by default in the Trust Center and enable them only for files you’ve verified.
- Never store tokens in the workbook or in code. When using environment variables, confirm other users cannot read them.
7. Performance Measurement and Tuning
Performance discussions should be grounded in measurements. Ollama’s non-streaming response includes total_duration, eval_count, and eval_duration, all in nanoseconds. Compute generation speed as:
Generation speed (tokens/s) = eval_count ÷ (eval_duration ÷ 1,000,000,000)
During testing, run the same set of questions five times and average the results while watching memory and VRAM usage in Task Manager; nvidia-smi shows actual VRAM consumption.
Common tuning directions:
- Choose an appropriate model size. 7B models respond faster on consumer GPUs and suit simple Q&A; 14B models are higher quality but need more resources.
- Control output length.
num_predictcaps the maximum tokens generated, keeping long replies from slowing the UI. - Choose quantization carefully. The default 4-bit quantization balances speed and quality well; don’t switch to higher precision without a specific need.
- Limit concurrency. When multiple users hit the same service, requests queue up—cap concurrency based on your hardware.
8. Troubleshooting Common Errors
- Request fails with a connection error: confirm Ollama is running, that
ollama listshows the model, and that your firewall isn’t blocking port 11434. - HTTP 404: verify the endpoint path is
/api/chatand thatLLM_ENDPOINTcontains no stray characters. - HTTP 400: usually means the request body isn’t valid JSON. Check that user input went through
JsonEscapeand that the model name matches one inollama list. - A4 is empty: no
contentfield was found in the response; printrespto the debug window to inspect the actual structure. - Garbled text: confirm the request headers include
charset=utf-8and that the worksheet cell fonts support the language being displayed.
9. Extension Ideas
The core of this solution is a closed loop of “ask, call, display,” which makes it easy to migrate to other scenarios. In Word you could generate document summaries; in Access, batch-process records. To answer questions based on local documents, you could build a vector index over the documents first, then feed retrieved passages to the model as context. All of these extensions build on the bridge layer from this article, adding only retrieval and context-assembly logic.
The main value of local deployment plus Excel integration is that users can tap into the model from a familiar interface without learning new tools, while keeping the data processing boundary easy to control. Following the steps above, you’ll have a working, verifiable, and extensible baseline implementation.
