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.

    1. 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.
    2. 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.
    3. 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.
    4. 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:

    1. ollama pull qwen2.5:7b
    2. ollama 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:

    1. 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:

    1. 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:

    1. 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.

    1. Option Explicit
    2. Sub AskLocalLLM()
    3. Dim ws As Worksheet
    4. Dim question As String, url As String, apiKey As String
    5. Dim body As String, answer As String
    6. Dim http As Object
    7. Dim attempt As Long, sendErr As Long, status As Long
    8. Set ws = ThisWorkbook.Sheets("Q&A")
    9. question = Trim(ws.Range("A2").Value)
    10. If question = "" Then
    11. ws.Range("A4").Value = "Please enter a question in cell A2 first"
    12. Exit Sub
    13. End If
    14. url = ThisWorkbook.Sheets("Config").Range("B1").Value
    15. apiKey = Environ("LLM_API_KEY")
    16. If url = "" Or apiKey = "" Then
    17. ws.Range("A4").Value = "Missing endpoint URL or LLM_API_KEY environment variable"
    18. Exit Sub
    19. End If
    20. body = "{""message"":""" & JsonEscape(question) & """,""mode"":""chat""}"
    21. For attempt = 1 To 3
    22. Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    23. http.setTimeouts 5000, 5000, 10000, 120000
    24. http.Open "POST", url, False
    25. http.setRequestHeader "Content-Type", "application/json; charset=utf-8"
    26. http.setRequestHeader "Authorization", "Bearer " & apiKey
    27. On Error Resume Next
    28. http.send body
    29. sendErr = Err.Number
    30. Err.Clear
    31. On Error GoTo 0
    32. If sendErr = 0 Then
    33. status = http.Status
    34. If status = 200 Then Exit For
    35. If status <> 429 And status < 500 Then Exit For
    36. End If
    37. If attempt < 3 Then Application.Wait Now + TimeSerial(0, 0, CLng(2 ^ attempt))
    38. Next attempt
    39. If sendErr <> 0 Then
    40. ws.Range("A4").Value = "Request failed: network error or timeout"
    41. ElseIf status = 200 Then
    42. answer = GetJsonString(http.responseText, "textResponse")
    43. If answer = "" Then
    44. ws.Range("A4").Value = "Could not parse the response. Check the API return format"
    45. Else
    46. ws.Range("A4").Value = "'" & answer ' Leading apostrophe prevents a reply starting with "=" from being interpreted as a formula
    47. End If
    48. Else
    49. ws.Range("A4").Value = "API request failed, status code: " & status & " " & http.statusText
    50. End If
    51. End Sub
    52. ' Escape special characters in the request body to prevent quotes or newlines from breaking the JSON structure
    53. Function JsonEscape(ByVal s As String) As String
    54. s = Replace(s, "\", "\\")
    55. s = Replace(s, """", "\""")
    56. s = Replace(s, vbCr, "\r")
    57. s = Replace(s, vbLf, "\n")
    58. s = Replace(s, vbTab, "\t")
    59. JsonEscape = s
    60. End Function
    61. ' Extract a string value for the given key from JSON text and restore escaped characters
    62. Function GetJsonString(ByVal json As String, ByVal key As String) As String
    63. Dim startPos As Long, i As Long
    64. Dim ch As String, nxt As String, buf As String, hex4 As String
    65. startPos = InStr(1, json, """" & key & """:""")
    66. If startPos = 0 Then Exit Function
    67. i = startPos + Len(key) + 4
    68. Do While i <= Len(json)
    69. ch = Mid$(json, i, 1)
    70. If ch = """" Then Exit Do
    71. If ch = "\" Then
    72. nxt = Mid$(json, i + 1, 1)
    73. Select Case nxt
    74. Case "n": buf = buf & vbLf
    75. Case "r": buf = buf & vbCr
    76. Case "t": buf = buf & vbTab
    77. Case "u"
    78. hex4 = Mid$(json, i + 2, 4)
    79. buf = buf & ChrW(CLng("&H" & hex4))
    80. i = i + 4
    81. Case Else: buf = buf & nxt
    82. End Select
    83. i = i + 2
    84. Else
    85. buf = buf & ch
    86. i = i + 1
    87. End If
    88. Loop
    89. GetJsonString = buf
    90. End 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:

    1. Application.ScreenUpdating = False
    2. Application.Calculation = xlCalculationManual
    3. ' Loop through the Q&A logic here
    4. Application.Calculation = xlCalculationAutomatic
    5. Application.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.1 unless 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.