Running a Local LLM in Spreadsheets: A Practical VBA Guide
Learn how to connect a locally running large language model to Excel with VBA. This step-by-step guide covers a four-layer architecture using Ollama and AnythingLLM, deployment and connectivity testing, a complete VBA macro with error handling and retry logic, batch processing tips, troubleshooting common errors, and key security practices.
Introduction
Once a large language model is running locally, the real challenge is integrating it into daily work. Many business users spend hours in Excel organizing customer messages, summarizing meeting notes, and writing product description summaries—repetitive tasks that are perfect candidates for an LLM. This article presents a practical, deployable solution: the model runs on your machine, a middleware layer exposes a unified API, and an Excel macro sends requests and writes responses back into cells.
The steps below use Ollama and AnythingLLM as examples. You can substitute your preferred model engine or gateway, but the API invocation approach remains the same.
1. Understanding the Four-Layer Architecture
The solution consists of four layers, each with a single responsibility.
- Model runtime engine: Loads the model weights into GPU or memory and performs inference. Ollama is a common choice, listening by default at
http://localhost:11434. - Model weights: Choose a model based on available VRAM. A 7B-parameter model, for example, needs roughly 5 GB of VRAM in its 4-bit quantized form, which runs on most consumer GPUs. More aggressive quantization uses less memory but degrades response quality—compare a few real prompts to find your trade-off.
- API middleware: Tools like AnythingLLM add a layer in front of the model, providing workspace isolation, API key authentication, and a unified chat endpoint. The business side only needs to know one address and one key, so swapping models doesn’t affect the macro code.
- Business layer: The Excel VBA macro. It reads the question from a cell, sends the request, and writes the result back to the sheet.
This layering makes troubleshooting straightforward. If the model fails to load, the problem is in layer one; a 401 response usually means a wrong API key; garbled text or parsing failures in the macro point to layer four.
2. Deployment and Connectivity Testing
Test each step before moving to the next. Jumping straight into debugging macro code makes it hard to tell which layer is failing.
Step 1: Start the model engine. After installing Ollama, run the following commands to download the model and start the service:
ollama pull qwen2.5:7bollama serve
Step 2: Test the model itself. Use this request to confirm the model responds. Setting stream to false returns a single complete JSON object:
curl http://localhost:11434/api/generate -d "{\"model\":\"qwen2.5:7b\",\"prompt\":\"Hello\",\"stream\":false}"
On Windows, if escaping fails in Command Prompt, use PowerShell instead, or write the JSON to a file and send it with curl -d @filename.
Step 3: Configure the middleware. After installing AnythingLLM, select Ollama as the LLM provider in the settings page, enter http://localhost:11434 as the Base URL, and choose the model you just downloaded. Then create a new workspace and note its slug—the workspace identifier shown in the browser address bar. Finally, generate an API key in the settings.
Step 4: Test the middleware API. AnythingLLM listens on port 3001 by default. The following request uses the non-streaming chat endpoint, with the reply returned in the JSON textResponse field:
curl -X POST http://localhost:3001/api/v1/workspace/your-slug/chat -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"message\":\"Hello\",\"mode\":\"chat\"}"
Endpoint paths and field names should match the API documentation for your version, as paths may change between releases.
One important note: a streaming endpoint such as stream-chat returns the reply in multiple event chunks, while a synchronous HTTP request only populates responseText after the entire response arrives—these require different reading approaches. For an Excel macro, the non-streaming endpoint is simpler and makes errors easier to diagnose.
Step 5: Save the configuration in Excel. Create a worksheet named “Config” and enter the full endpoint URL in cell B1, for example http://localhost:3001/api/v1/workspace/your-slug/chat. Do not store the API key in the workbook; save it as a system environment variable instead. Run the following command and restart Excel:
setx LLM_API_KEY "YOUR_API_KEY"
3. Implementing the VBA Macro
The macro reads a question from cell A2 of the “Q&A” worksheet, calls the API, and writes the answer to cell A4. The code has three parts: the main procedure handles the flow, JsonEscape escapes the request body, and GetJsonString extracts the text from the response.
Option ExplicitSub AskLocalLLM()Dim ws As WorksheetDim question As String, url As String, apiKey As StringDim body As String, answer As StringDim http As ObjectDim attempt As Long, sendErr As Long, status As LongSet ws = ThisWorkbook.Sheets("Q&A")question = Trim(ws.Range("A2").Value)If question = "" Thenws.Range("A4").Value = "Please enter a question in cell A2 first"Exit SubEnd Ifurl = ThisWorkbook.Sheets("Config").Range("B1").ValueapiKey = Environ("LLM_API_KEY")If url = "" Or apiKey = "" Thenws.Range("A4").Value = "Missing endpoint URL or LLM_API_KEY environment variable"Exit SubEnd Ifbody = "{""message"":""" & JsonEscape(question) & """,""mode"":""chat""}"For attempt = 1 To 3Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")http.setTimeouts 5000, 5000, 10000, 120000http.Open "POST", url, Falsehttp.setRequestHeader "Content-Type", "application/json; charset=utf-8"http.setRequestHeader "Authorization", "Bearer " & apiKeyOn Error Resume Nexthttp.send bodysendErr = Err.NumberErr.ClearOn Error GoTo 0If sendErr = 0 Thenstatus = http.StatusIf status = 200 Then Exit ForIf status <> 429 And status < 500 Then Exit ForEnd IfIf attempt < 3 Then Application.Wait Now + TimeSerial(0, 0, CLng(2 ^ attempt))Next attemptIf sendErr <> 0 Thenws.Range("A4").Value = "Request failed: network error or timeout"ElseIf status = 200 Thenanswer = GetJsonString(http.responseText, "textResponse")If answer = "" Thenws.Range("A4").Value = "Could not parse the response. Check the API return format"Elsews.Range("A4").Value = "'" & answer ' Leading apostrophe prevents a reply starting with "=" from being interpreted as a formulaEnd IfElsews.Range("A4").Value = "API request failed, status code: " & status & " " & http.statusTextEnd IfEnd Sub' Escape special characters in the request body to prevent quotes or newlines from breaking the JSON structureFunction JsonEscape(ByVal s As String) As Strings = Replace(s, "\", "\\")s = Replace(s, """", "\""")s = Replace(s, vbCr, "\r")s = Replace(s, vbLf, "\n")s = Replace(s, vbTab, "\t")JsonEscape = sEnd Function' Extract a string value for the given key from JSON text and restore escaped charactersFunction GetJsonString(ByVal json As String, ByVal key As String) As StringDim startPos As Long, i As LongDim ch As String, nxt As String, buf As String, hex4 As StringstartPos = InStr(1, json, """" & key & """:""")If startPos = 0 Then Exit Functioni = startPos + Len(key) + 4Do While i <= Len(json)ch = Mid$(json, i, 1)If ch = """" Then Exit DoIf ch = "\" Thennxt = Mid$(json, i + 1, 1)Select Case nxtCase "n": buf = buf & vbLfCase "r": buf = buf & vbCrCase "t": buf = buf & vbTabCase "u"hex4 = Mid$(json, i + 2, 4)buf = buf & ChrW(CLng("&H" & hex4))i = i + 4Case Else: buf = buf & nxtEnd Selecti = i + 2Elsebuf = buf & chi = i + 1End IfLoopGetJsonString = bufEnd Function
Several design decisions deserve explanation.
Timeout settings. The XMLHTTP object has no timeout parameters, so if the model responds slowly, the macro waits indefinitely and Excel freezes. ServerXMLHTTP allows separate timeouts for resolution, connection, sending, and receiving. The receive timeout here is 120 seconds, because a local LLM running short on VRAM may take a long time to generate a reply.
Retry strategy. On network errors, 429 (too many requests), or 5xx (server errors), the macro waits 2 seconds, then 4 seconds, retrying up to three times. For definitive client errors like 401 or 404, retrying is pointless, so the macro reports the result immediately.
Request body escaping. If the question in A2 contains double quotes or line breaks, naive string concatenation produces invalid JSON. JsonEscape handles backslashes first, then quotes and line breaks—this order cannot be reversed.
Response parsing. The GetJsonString function assumes no space after the colon, which matches the compact JSON format returned by most servers. If your middleware returns JSON with spaces, adjust the match string in the startPos line accordingly. It handles \n, \", \\, and \uXXXX escapes, which covers common responses.
4. Batch Processing and Performance
In practice, you rarely ask just one question. When processing hundreds of rows, keep two things in mind.
First, a synchronous call blocks Excel. A single reply may take seconds to tens of seconds, during which the sheet is unresponsive. Before looping, disable screen updating and automatic calculation:
Application.ScreenUpdating = FalseApplication.Calculation = xlCalculationManual' Loop through the Q&A logic hereApplication.Calculation = xlCalculationAutomaticApplication.ScreenUpdating = True
Second, show progress during the loop. Use Application.StatusBar to display “Processing row n of m” in the status bar. Consider saving the workbook roughly every 100 rows so that completed results aren’t lost if an error occurs midway.
Also control concurrency in batch jobs. A local model can typically handle only one or two requests efficiently—firing off many requests at once just queues them, so synchronous, one-by-one calls are actually more reliable.
5. Troubleshooting Common Errors
The table below lists the most common issues and how to check them.
| Symptom | Likely Cause | How to Check |
|---|---|---|
| Status code 401 | Wrong key, or environment variable not applied | Verify the key in middleware settings; restart Excel and retry |
| Status code 404 | Wrong workspace slug or endpoint path | Compare the slug in the address bar with the API documentation and update cell B1 |
| Connection refused | Model engine or middleware not running | Test with the curl commands from Step 2 and Step 4 |
| Request timeout | Model too large, insufficient VRAM, or reply too long | Switch to a smaller model or lower quantization level, and increase the timeout |
| “Could not parse” message | Field name or JSON format mismatch | Use Debug.Print to output http.responseText and inspect the actual structure |
| Garbled text | Request header encoding mismatch | Confirm charset=utf-8 in the request header and check the middleware’s encoding settings |
If error messages aren’t enough to locate the problem, write http.responseText along with the request body to a log worksheet. Keeping the raw response usually saves most of the debugging time.
6. Security Considerations
Local deployment doesn’t mean zero risk. Other devices on the local network may still be able to reach the middleware, so keep the following in mind.
- Middleware must have authentication enabled, and should listen only on
127.0.0.1unless you explicitly need LAN sharing. - Store API keys only in environment variables—never in the workbook, never in the code, and never distribute them with the spreadsheet file.
- Spreadsheets containing customer privacy or internal financial data should be processed on an offline machine, ensuring data never leaves the local machine or intranet.
- When sharing macro-enabled files with colleagues, have each person configure their own key rather than exposing yours.
7. Conclusion
The local model, middleware, and Excel macro each carry clear responsibilities, connected through a single HTTP interface. Following the order in this article—testing the model first, then the middleware, then the macro—lets you isolate failures to a specific layer quickly and build a reliable AI-powered spreadsheet workflow.
