Local LLMs in Practice: Build a Private Spreadsheet AI Assistant with VBA

    Learn how to connect a spreadsheet to a locally hosted large language model using VBA and an HTTP API. This guide covers the architecture, setup, and code for reading a question from a cell and writing the model’s answer back to the workbook. It also explains how to extend the workflow to batch processing, structured output, and private knowledge-base queries.

    1. What Can You Do with a Local LLM?

    A locally hosted large language model (LLM) can do more than answer questions in a chat window. When the supporting services also run locally, it can help with several kinds of work without sending sensitive data to an external service:

    1. Private Q&A and knowledge retrieval: Connect the model to a local knowledge base so employees can ask questions about internal documents, policies, and technical reference material.
    2. Office automation: Integrate the model with spreadsheets and document tools to process text in batches, generate content, and explain data.
    3. Software development assistance: Use the model for code completion, review, and comment generation without sending source code to an external service.
    4. Workflow integration: Use an API to add model-powered features to existing systems, such as ticket summaries, first drafts of reports, and email drafts.

    This guide focuses on one straightforward integration: using VBA to bring a local model into a spreadsheet workflow. Enter a question in one cell, click a button, and the macro writes the answer to another cell. The entire request stays local in this setup.

    2. How the Spreadsheet Assistant Works

    The design separates the workbook, the application framework, and the model runtime:

    • Model inference layer: A local inference service loads and runs the model and exposes an HTTP interface.
    • Application orchestration layer: A local chat and knowledge-base framework manages workspaces and conversation context, and provides an API for the spreadsheet.
    • Client layer: The spreadsheet is the user interface. Its VBA macro reads the question, sends it to the API, and writes back the answer.
    • Request flow: VBA macro → local framework API → inference service → model response → spreadsheet cell.

    Keeping these components separate makes them easier to replace. For example, you can switch models in the inference layer without changing the workbook macro, as long as the framework’s API stays the same.

    3. Set Up the Local Environment

    Install a local inference service

    Choose and install a local model runtime. These tools typically provide a command-line interface for downloading model weights. Choose a model that fits your hardware:

    • If you have sufficient RAM or VRAM—16 GB or more as a rough starting point—consider a larger model for potentially better answers.
    • If memory is limited, start with a smaller, quantized model to keep response times practical.
    • Test the full request flow with a small model before moving to a larger one.

    Install a chat and knowledge-base framework

    Choose a framework that can connect to your local inference service. It sits between the spreadsheet and the model, providing workspace management, document import, multi-turn conversations, and an HTTP API.

    Configure the framework

    In the framework’s settings:

    1. Enter the inference service address in the model provider settings. This is typically a loopback address and port.
    2. Select the model you want to use.
    3. If you want answers based on internal documents, import them into a private knowledge base.
    4. Generate an API key for requests from the VBA macro.

    Prepare the spreadsheet

    Use a spreadsheet application that supports VBA and can access the MSXML2.XMLHTTP system component. The macro uses this component to send HTTP requests, so it does not need a separate networking library.

    4. Call the Local Model from VBA

    Press Alt + F11 to open the VBA editor, then insert a module. The macro below reads a question from cell A2 on the first worksheet, sends it to the local workspace, and writes the parsed answer to A4. Replace the API key placeholder and use the workspace identifier expected by your framework, including the correct capitalization.

    1. Sub CallLocalModel()
    2. Dim question As String
    3. Dim response As String
    4. Dim url As String
    5. Dim apiKey As String
    6. Dim http As Object
    7. Dim requestBody As String
    8. ' Read the question from cell A2.
    9. question = ThisWorkbook.Sheets(1).Range("A2").Value
    10. ' Set the local chat endpoint. Match the workspace identifier's case.
    11. url = "http://localhost:3001/api/v1/workspace/myworkspace/stream-chat"
    12. apiKey = "YOUR_API_KEY"
    13. ' Configure the HTTP request.
    14. Set http = CreateObject("MSXML2.XMLHTTP")
    15. http.Open "POST", url, False
    16. http.setRequestHeader "accept", "text/event-stream"
    17. http.setRequestHeader "Content-Type", "application/json"
    18. http.setRequestHeader "Authorization", "Bearer " & apiKey
    19. ' Build the JSON request body.
    20. requestBody = "{""message"":""" & question & """,""mode"":""chat""}"
    21. http.send requestBody
    22. If http.Status = 200 Then
    23. response = http.responseText
    24. ' Parse the response and write the answer to cell A4.
    25. ThisWorkbook.Sheets(1).Range("A4").Value = ParseResponse(response)
    26. Else
    27. MsgBox "Request failed. HTTP status: " & http.Status
    28. End If
    29. End Sub

    The endpoint returns server-sent events. In the response format shown here, lines beginning with data: carry JSON, and the textResponse fields contain fragments of the answer. The parser scans the returned text and concatenates those fragments in order. This example shows the parsing loop; the ExtractField helper is not included and must extract and decode the JSON string value.

    1. Function ParseResponse(ByVal raw As String) As String
    2. Dim lines() As String, i As Long
    3. Dim result As String, pos As Long, fragment As String
    4. lines = Split(raw, vbLf)
    5. For i = LBound(lines) To UBound(lines)
    6. If InStr(lines(i), """textResponse""") > 0 Then
    7. ' Extract the textResponse value and append it to the answer.
    8. result = result & ExtractField(lines(i), """textResponse"":""")
    9. End If
    10. Next i
    11. ParseResponse = result
    12. End Function

    Before using the macro in a daily workflow, address four practical details:

    1. Escape JSON input. The example builds the request body by concatenating strings. Escape quotation marks, backslashes, and line breaks in the question before inserting it into the JSON body.
    2. Keep the workbook responsive. The request is synchronous, so the spreadsheet waits for it to finish even though the endpoint returns a stream. Use an asynchronous request with a callback if long answers make the interface unresponsive.
    3. Handle failures. Add timeout and error handling for connection failures as well as unsuccessful HTTP statuses, so users get useful feedback when the local service is unavailable.
    4. Assign the macro to a button. Insert a worksheet button and assign it to CallLocalModel. Users can then enter a question in A2, click the button, and read the answer in A4.

    5. Extend the Workflow

    Once the single-cell example works, adapt it to other spreadsheet tasks:

    • Batch processing: Put questions or source text in a column and loop through the rows for tasks such as summarizing, translating, or classifying entries.
    • Structured output: Ask the model to return JSON or tabular data in a fixed format, then parse the response and populate multiple cells.
    • Private knowledge-base Q&A: Import product manuals, internal policies, or other reference documents so users can ask questions about them from the workbook.
    • API key protection: Keeping the workflow local reduces the need to send sensitive data outside your environment, but the API key still needs protection. Do not hard-code it in a workbook you distribute.

    6. Takeaway

    The value of running an LLM locally is being able to add AI to a workflow you already use while retaining control over where the data goes. A spreadsheet and a short VBA macro are a practical starting point: read input, send it to a local API, and write the result back where the user needs it. The same pattern can be applied to other business tools that support HTTP requests.