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:

    1. 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):
    1. {"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:

    1. Private Const MAX_RETRY As Long = 3
    2. ' Batch processing: read questions from column A, write replies to column B, status to column C
    3. Public Sub BatchAsk()
    4. Dim ws As Worksheet
    5. Dim lastRow As Long
    6. Dim r As Long
    7. Dim question As String
    8. Dim answer As String
    9. Dim errMsg As String
    10. Set ws = ThisWorkbook.Sheets("问答")
    11. lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    12. For r = 2 To lastRow ' Row 1 is the header
    13. question = Trim(ws.Cells(r, "A").Value)
    14. If question <> "" And ws.Cells(r, "B").Value = "" Then
    15. If AskLLM(question, answer, errMsg) Then
    16. ws.Cells(r, "B").Value = answer
    17. ws.Cells(r, "C").Value = "Success"
    18. Else
    19. ws.Cells(r, "C").Value = "Failed: " & errMsg
    20. End If
    21. DoEvents ' Refresh the UI to avoid a frozen window
    22. End If
    23. Next r
    24. MsgBox "Processing complete", vbInformation
    25. End Sub
    26. ' Single Q&A call with built-in retries. Returns True on success; the reply is returned via answer
    27. Public Function AskLLM(ByVal question As String, ByRef answer As String, ByRef errMsg As String) As Boolean
    28. Dim url As String, apiKey As String, body As String
    29. Dim http As Object
    30. Dim attempt As Long, status As Long
    31. Dim respText As String, errDesc As String
    32. url = Environ("LLM_CHAT_URL")
    33. apiKey = Environ("LLM_API_KEY")
    34. If url = "" Or apiKey = "" Then
    35. errMsg = "Environment variables LLM_CHAT_URL or LLM_API_KEY are not set"
    36. Exit Function
    37. End If
    38. body = "{""message"":""" & JsonEscape(question) & """,""mode"":""chat""}"
    39. For attempt = 1 To MAX_RETRY
    40. status = 0
    41. respText = ""
    42. errDesc = ""
    43. On Error Resume Next
    44. Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    45. http.setTimeouts 5000, 5000, 10000, 120000 ' Resolve, connect, send, receive timeouts in ms
    46. http.Open "POST", url, False
    47. http.setRequestHeader "Accept", "application/json"
    48. http.setRequestHeader "Content-Type", "application/json; charset=utf-8"
    49. http.setRequestHeader "Authorization", "Bearer " & apiKey
    50. http.send body
    51. If Err.Number = 0 Then
    52. status = http.Status
    53. respText = http.responseText
    54. Else
    55. errDesc = Err.Description
    56. End If
    57. Err.Clear
    58. On Error GoTo 0
    59. If status = 200 Then
    60. answer = ExtractTextResponse(respText)
    61. If answer <> "" Then
    62. AskLLM = True
    63. Else
    64. errMsg = "textResponse field not found in the response"
    65. End If
    66. Exit Function
    67. ElseIf status >= 400 And status < 500 Then
    68. errMsg = "HTTP " & status & ", check the URL, workspace slug, and API Key"
    69. Exit Function ' Retrying a client error is pointless; return immediately
    70. Else
    71. errMsg = "Attempt " & attempt & " failed: " & IIf(status = 0, errDesc, "HTTP " & status)
    72. Application.Wait Now + TimeSerial(0, 0, 2 * attempt) ' Wait with increasing delay, then retry
    73. End If
    74. Next attempt
    75. End Function
    76. ' Escape special characters in a JSON string so quotes or newlines in the question don't break the request body
    77. Public Function JsonEscape(ByVal s As String) As String
    78. s = Replace(s, "\", "\\") ' Backslashes must be handled first
    79. s = Replace(s, """", "\""")
    80. s = Replace(s, vbCrLf, "\n")
    81. s = Replace(s, vbCr, "\n")
    82. s = Replace(s, vbLf, "\n")
    83. s = Replace(s, vbTab, "\t")
    84. JsonEscape = s
    85. End Function
    86. ' Extract the top-level textResponse field from the response JSON and unescape escape sequences
    87. Public Function ExtractTextResponse(ByVal body As String) As String
    88. Dim key As String, p As Long, i As Long, code As Long
    89. Dim ch As String, nxt As String, out As String
    90. key = """textResponse"""
    91. p = InStr(1, body, key)
    92. If p = 0 Then Exit Function
    93. p = InStr(p + Len(key), body, ":")
    94. If p = 0 Then Exit Function
    95. i = p + 1
    96. Do While Mid$(body, i, 1) = " " ' Skip spaces after the colon
    97. i = i + 1
    98. Loop
    99. If Mid$(body, i, 1) <> """" Then Exit Function ' Return empty if the field is null or not a string
    100. i = i + 1
    101. Do While i <= Len(body)
    102. ch = Mid$(body, i, 1)
    103. If ch = """" Then Exit Do
    104. If ch = "\" Then
    105. nxt = Mid$(body, i + 1, 1)
    106. Select Case nxt
    107. Case "n": out = out & vbLf
    108. Case "r": out = out & vbCr
    109. Case "t": out = out & vbTab
    110. Case "u"
    111. code = CLng("&H" & Mid$(body, i + 2, 4))
    112. If code > 32767 Then code = code - 65536
    113. out = out & ChrW(code)
    114. i = i + 4
    115. Case Else: out = out & nxt ' Handles \" \\ \/ etc.
    116. End Select
    117. i = i + 2
    118. Else
    119. out = out & ch
    120. i = i + 1
    121. End If
    122. Loop
    123. ExtractTextResponse = out
    124. End 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…