Calling a Locally Deployed LLM from a Spreadsheet: Batch Q&A with Excel VBA
After deploying a large language model locally, the real work has only just begun. This article shows how to connect a local LLM to a spreadsheet via a gateway layer, with complete VBA code for batch question answering, result write-back, retry logic, and robust error handling, plus guidance on logging and cloud monitoring. Finishing the local deployment is only step one; many people stop at command-line chat, while their actual data-cleaning and Q&A work happens in office software. Using spreadsheets as the example, this guide explains how to call a local model from Excel to run batch queries and write results back into cells.
Calling a Locally Deployed LLM from a Spreadsheet
Finishing the local deployment of a large language model is only the beginning. Many people stop at chatting from the command line, but everyday data-cleaning and Q&A needs happen inside office software. This article uses a spreadsheet as the example to show how to connect a local model to Excel, enabling batch Q&A and writing results back into cells.
1. Architecture and Environment Setup
To let office software use a local model, you need a three-layer structure: a local model runtime at the bottom, a gateway layer providing a unified API in the middle, and the spreadsheet with macro code on top. Each layer has clear responsibilities, so problems can be isolated layer by layer.
1.1 Set Up the Local Model Runtime
First, install a model runtime on your machine and choose an open-source model whose parameter size fits your GPU memory and RAM. If VRAM is limited, pick a smaller model or a quantized version—otherwise inference speed will drop noticeably. After loading the model, confirm the runtime responds reliably to local requests. This layer is the compute foundation of the whole system; every call ultimately ends here for inference.
1.2 Deploy the Middle-Layer Gateway
The API built into a model runtime usually handles inference only. It lacks context management, knowledge base mounting, multi-user key management, and similar features. A middle-layer gateway fills these gaps: it connects downward to the model runtime and exposes a unified HTTP interface upward to clients. For a common knowledge-base-style gateway, the default service port might be 3001—refer to the official documentation of the product you use for the actual port and API paths. In the gateway, enter the address of your local model and select the default model instance to call.
1.3 Prepare the Office Side
In the spreadsheet application, enable the Developer tab and configure macro behavior in the Trust Center. Enable macros only for trusted files; do not loosen restrictions globally. The code in this article sends requests using MSXML2.ServerXMLHTTP.6.0, a component built into Windows, so no third-party libraries or references are needed.
2. API Configuration and Connectivity Testing
2.1 Create a Workspace and API Key
In the gateway’s settings page, create a new workspace and note its identifier (slug). The slug must be lowercase and match the name in the API path exactly. Then generate an API Key under that workspace. The key is the caller’s credential; grant it access to this workspace only, not full permissions.
2.2 Note the Endpoint Address
For a local deployment, the endpoint typically looks like this:
http://localhost:3001/api/v1/workspace/your-workspace-slug/chat
The gateway provides two chat endpoints. /chat returns a complete JSON object after the model finishes generating its reply. /stream-chat returns content incrementally in text/event-stream format, requiring the client to parse events one by one. The macro code in this article uses /chat because its response structure is simple, no stream handling is required, and it is better suited to writing results row by row in a spreadsheet.
2.3 Verify Connectivity with Postman
Before writing any code, use Postman to confirm the chain works. Configure the request as follows:
- Method:
POST - Headers:
Accept: application/json,Content-Type: application/json,Authorization: Bearer your-API-Key - Body (raw, JSON):
{"message": "Introduce yourself in one sentence", "mode": "chat"}
Under normal conditions, the response returns HTTP 200 and the JSON contains a textResponse field holding the model’s reply. A 401 usually means the API Key is wrong or expired; a 404 usually means the workspace slug is misspelled; a 500 means you should check whether the model runtime has loaded successfully. Once all three checks pass, move on to the code.
2.4 Protecting Keys and Addresses
API Keys should never be written into code, cells, or logs. The code in this article reads two settings from system environment variables: LLM_CHAT_URL for the endpoint address and LLM_API_KEY for the key. On Windows, open System Properties, go to the Advanced tab, click Environment Variables, and add both under user variables. Restart Excel afterward for the new variables to take effect.
3. Macro Implementation and Explanation
The worksheet layout is defined as follows: the sheet is named “QA” (问答), column A holds questions, column B receives the model’s replies, and column C records processing status. The code skips rows that already have content in column B, so failed rows can simply be re-run without re-calling successful ones.
Below is the complete VBA code, ready to paste into a standard module:
Private Const MAX_RETRY As Long = 3' Batch processing: read questions from column A, write replies to column B, status to column CPublic Sub BatchAsk()Dim ws As WorksheetDim lastRow As LongDim r As LongDim question As StringDim answer As StringDim errMsg As StringSet ws = ThisWorkbook.Sheets("问答")lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).RowFor r = 2 To lastRow ' Row 1 is the headerquestion = Trim(ws.Cells(r, "A").Value)If question <> "" And ws.Cells(r, "B").Value = "" ThenIf AskLLM(question, answer, errMsg) Thenws.Cells(r, "B").Value = answerws.Cells(r, "C").Value = "Success"Elsews.Cells(r, "C").Value = "Failed: " & errMsgEnd IfDoEvents ' Refresh the UI to avoid a frozen windowEnd IfNext rMsgBox "Processing complete", vbInformationEnd Sub' Single Q&A call with built-in retries. Returns True on success; the reply is returned via answerPublic Function AskLLM(ByVal question As String, ByRef answer As String, ByRef errMsg As String) As BooleanDim url As String, apiKey As String, body As StringDim http As ObjectDim attempt As Long, status As LongDim respText As String, errDesc As Stringurl = Environ("LLM_CHAT_URL")apiKey = Environ("LLM_API_KEY")If url = "" Or apiKey = "" ThenerrMsg = "Environment variables LLM_CHAT_URL or LLM_API_KEY are not set"Exit FunctionEnd Ifbody = "{""message"":""" & JsonEscape(question) & """,""mode"":""chat""}"For attempt = 1 To MAX_RETRYstatus = 0respText = ""errDesc = ""On Error Resume NextSet http = CreateObject("MSXML2.ServerXMLHTTP.6.0")http.setTimeouts 5000, 5000, 10000, 120000 ' Resolve, connect, send, receive timeouts in mshttp.Open "POST", url, Falsehttp.setRequestHeader "Accept", "application/json"http.setRequestHeader "Content-Type", "application/json; charset=utf-8"http.setRequestHeader "Authorization", "Bearer " & apiKeyhttp.send bodyIf Err.Number = 0 Thenstatus = http.StatusrespText = http.responseTextElseerrDesc = Err.DescriptionEnd IfErr.ClearOn Error GoTo 0If status = 200 Thenanswer = ExtractTextResponse(respText)If answer <> "" ThenAskLLM = TrueElseerrMsg = "textResponse field not found in the response"End IfExit FunctionElseIf status >= 400 And status < 500 ThenerrMsg = "HTTP " & status & ", check the URL, workspace slug, and API Key"Exit Function ' Retrying a client error is pointless; return immediatelyElseerrMsg = "Attempt " & attempt & " failed: " & IIf(status = 0, errDesc, "HTTP " & status)Application.Wait Now + TimeSerial(0, 0, 2 * attempt) ' Wait with increasing delay, then retryEnd IfNext attemptEnd Function' Escape special characters in a JSON string so quotes or newlines in the question don't break the request bodyPublic Function JsonEscape(ByVal s As String) As Strings = Replace(s, "\", "\\") ' Backslashes must be handled firsts = Replace(s, """", "\""")s = Replace(s, vbCrLf, "\n")s = Replace(s, vbCr, "\n")s = Replace(s, vbLf, "\n")s = Replace(s, vbTab, "\t")JsonEscape = sEnd Function' Extract the top-level textResponse field from the response JSON and unescape escape sequencesPublic Function ExtractTextResponse(ByVal body As String) As StringDim key As String, p As Long, i As Long, code As LongDim ch As String, nxt As String, out As Stringkey = """textResponse"""p = InStr(1, body, key)If p = 0 Then Exit Functionp = InStr(p + Len(key), body, ":")If p = 0 Then Exit Functioni = p + 1Do While Mid$(body, i, 1) = " " ' Skip spaces after the coloni = i + 1LoopIf Mid$(body, i, 1) <> """" Then Exit Function ' Return empty if the field is null or not a stringi = i + 1Do While i <= Len(body)ch = Mid$(body, i, 1)If ch = """" Then Exit DoIf ch = "\" Thennxt = Mid$(body, i + 1, 1)Select Case nxtCase "n": out = out & vbLfCase "r": out = out & vbCrCase "t": out = out & vbTabCase "u"code = CLng("&H" & Mid$(body, i + 2, 4))If code > 32767 Then code = code - 65536out = out & ChrW(code)i = i + 4Case Else: out = out & nxt ' Handles \" \\ \/ etc.End Selecti = i + 2Elseout = out & chi = i + 1End IfLoopExtractTextResponse = outEnd Function
The code has four parts. BatchAsk walks the sheet, processing only rows where column A has a question and column B is empty, then writes the result to column B and the status to column C. AskLLM handles a single request: it reads configuration from environment variables, sets timeouts, sends the request, and decides whether to succeed, retry, or fail immediately based on the status code. Network timeouts and 5xx errors are retried with increasing delays; 4xx errors return immediately because retrying won’t change the outcome. JsonEscape escapes quotes, backslashes, and newlines in the question before building the request body, preventing malformed JSON. ExtractTextResponse pulls the textResponse field out of the response and restores escape sequences such as \n, \", and \uXXXX—non-ASCII characters often appear this way in responses from some services.
This parsing function only targets a single top-level field, which is sufficient for this scenario. If the response structure is more complex, consider using an open-source VBA JSON parsing library to replace the hand-written parser.
4. Advanced Practices and Robustness Improvements
4.1 Performance and UI Responsiveness
ServerXMLHTTP is a synchronous call: each request blocks until the model responds, during which Excel is unresponsive. DoEvents keeps the UI refreshing but does not speed up processing. A local model typically runs on a single GPU with limited concurrency—sending multiple requests at once just queues them up and increases per-request latency. Small batches are therefore best run during off-peak times. For large batches, an offline Python script is a better fit: call the same endpoint with the requests library and read/write the workbook with openpyxl, which gives you flexible control over concurrency and progress. If you truly need asynchronous calls in VBA, MSXML2.XMLHTTP with callbacks is an option, but the implementation complexity is significantly higher.
4.2 Error Handling and Retry Strategy
The code divides errors into two categories. Timeouts, connection failures, and 5xx errors are transient and are retried automatically with increasing wait times. 4xx errors indicate a problem with the request itself—such as a wrong key or workspace slug—so retrying is useless; the code returns immediately and shows the reason in column C. After a batch run finishes, filter column C for rows that are not “Success”, fix the configuration, and run BatchAsk again to reprocess only the failed rows.
4.3 Log Archiving and Cloud Monitoring
For important data-processing tasks, local execution lacks traceability. Organizations can sync call records to the cloud for auditing and performance analysis—after first clarifying which data is allowed to leave the local environment.
- Recommended for upload: call timestamp, model name, latency, HTTP status code, token usage, and error type. These fields are enough for performance and failure analysis.
- Not uploaded by default: raw prompts and raw model replies. These often contain customer information and business data and require separate evaluation. If upload is truly necessary, desensitize first—for example, replace phone numbers, ID numbers, and customer names—and confirm the data usage is authorized.
- API Keys and sensitive parts of endpoint addresses must never appear in logs.
- Cloud access should use a sub-account with only the minimum permissions needed to write logs. Storage should have encryption and access auditing enabled, with a clearly defined retention period.
- If the data…
