Back

Office + AI Integration

VBA macros and Python bridge for Word & Excel with LLM connectivity (Ollama, ChatGPT, Claude)

Integration paths at a glance

1. Cloud Copilot

Microsoft 365 Copilot or ChatGPT plugin directly inside Word/Excel. Quick to set up, but data goes out.

2. VBA macro + API

Custom macro that sends selected text to an LLM API and inserts the result. Maximum control, but VBA maintenance.

3. Python bridge (local)

Local HTTP service (FastAPI) talks to Ollama or an API. Office calls it via VBA. Fully offline-capable.

Variant A: VBA macro directly to Claude / OpenAI

Simplest approach: a Word macro takes the selected text, sends it to the Claude or OpenAI API, and inserts the reply. The API key is stored as a Windows environment variable.

Word VBA macro (Claude API)

Sub AskClaude()
    Dim selText As String, prompt As String, resp As String
    If Selection.Type = wdSelectionNormal Then
        selText = Selection.Text
    Else
        MsgBox "Please select text.": Exit Sub
    End If

    prompt = InputBox("Instruction:", "Claude", "Rewrite in patent-style prose.")
    If prompt = "" Then Exit Sub

    resp = CallClaude(prompt & vbCrLf & vbCrLf & selText)
    Selection.TypeText resp
End Sub

Private Function CallClaude(userMsg As String) As String
    Dim xhr As Object, body As String, apiKey As String
    apiKey = Environ("ANTHROPIC_API_KEY")
    Set xhr = CreateObject("MSXML2.XMLHTTP")

    body = "{""model"":""claude-sonnet-4-6""," & _
           """max_tokens"":2048," & _
           """messages"":[{""role"":""user"",""content"":" & JsonStr(userMsg) & "}]}"

    xhr.Open "POST", "https://api.anthropic.com/v1/messages", False
    xhr.setRequestHeader "content-type", "application/json"
    xhr.setRequestHeader "x-api-key", apiKey
    xhr.setRequestHeader "anthropic-version", "2023-06-01"
    xhr.send body

    ' Minimal parsing: content[0].text
    Dim r As String: r = xhr.responseText
    Dim p As Long: p = InStr(r, """text"":""") + 8
    Dim q As Long: q = InStr(p, r, """")
    CallClaude = Replace(Mid(r, p, q - p), "\n", vbCrLf)
End Function

Private Function JsonStr(s As String) As String
    JsonStr = """" & Replace(Replace(s, "\", "\\"), """", "\""") & """"
End Function

Setup: Alt+F11 opens the VBA editor, insert a module, paste the code, set the API key as environment variable ANTHROPIC_API_KEY (or OPENAI_API_KEY), then expose the macro as a toolbar button or keyboard shortcut.

Variant B: Python bridge with local Ollama

For fully local processing: no data leaves the machine. A small FastAPI service runs in the background and dispatches Office requests to Ollama.

1. Bridge server (bridge.py)

from fastapi import FastAPI
from pydantic import BaseModel
import ollama

app = FastAPI()

class Req(BaseModel):
    instruction: str
    text: str
    model: str = "llama3.3:70b-instruct"

@app.post("/complete")
def complete(req: Req):
    resp = ollama.chat(
        model=req.model,
        messages=[
            {"role": "system", "content": "You are a patent-attorney assistant. Answer concisely."},
            {"role": "user", "content": f"{req.instruction}\n\nText:\n{req.text}"},
        ],
    )
    return {"reply": resp["message"]["content"]}

Start with uvicorn bridge:app --port 8765. Optionally auto-start on Windows login.

2. Word macro that calls the bridge

Sub AskLocal()
    Dim selText As String, instruction As String, resp As String
    selText = Selection.Text
    instruction = InputBox("Instruction:", "Local AI", "Rewrite.")
    If instruction = "" Then Exit Sub

    Dim xhr As Object: Set xhr = CreateObject("MSXML2.XMLHTTP")
    Dim body As String
    body = "{""instruction"":" & JsonStr(instruction) & _
           ",""text"":" & JsonStr(selText) & "}"

    xhr.Open "POST", "http://127.0.0.1:8765/complete", False
    xhr.setRequestHeader "content-type", "application/json"
    xhr.send body

    resp = xhr.responseText
    Dim p As Long: p = InStr(resp, """reply"":""") + 9
    Dim q As Long: q = InStrRev(resp, """")
    Selection.TypeText Replace(Mid(resp, p, q - p), "\n", vbCrLf)
End Sub

Excel: cell function =LLM(...)

With a user-defined function you can send any cell to the LLM, useful for tables of keywords, classifications, translations.

Public Function LLM(instruction As String, text As String) As String
    Dim xhr As Object: Set xhr = CreateObject("MSXML2.XMLHTTP")
    Dim body As String
    body = "{""instruction"":" & JsonStr(instruction) & _
           ",""text"":" & JsonStr(text) & "}"

    xhr.Open "POST", "http://127.0.0.1:8765/complete", False
    xhr.setRequestHeader "content-type", "application/json"
    xhr.send body

    Dim r As String: r = xhr.responseText
    Dim p As Long: p = InStr(r, """reply"":""") + 9
    Dim q As Long: q = InStrRev(r, """")
    LLM = Replace(Mid(r, p, q - p), "\n", " ")
End Function

In an Excel cell: =LLM("Classify as mechanics / electrical / software", A2)

Typical use cases in patent practice

Rewrite response to office action

Select draft → macro → smoother style, patent-typical language enforced.

Check feature breakdown

Select claim text + breakdown → "check completeness".

Excel: classify case list

=LLM function in a column → automatic sorting by technical field.

Translation DE ⇄ EN

Replace short passages in place; patent-typical terminology preserved.

MCP connectors for Claude Cowork

Claude Cowork (Desktop) can talk directly to Office products, email, and calendars via the Model Context Protocol (MCP), no macro required.

  • Microsoft 365 connector: reads/writes OneDrive, SharePoint, Outlook, Teams
  • Google Workspace: Drive, Gmail, Calendar
  • Gmail / Google Calendar: available individually
  • Box, Egnyte: for firms with their own document management
  • Slack, Atlassian: for internal communication / ticket systems

Details: see the Claude Code guide → section "Hooks & MCP" or the official documentation at docs.claude.com.

Data protection & security

  • Client confidentiality:* for case content, use the Ollama bridge (nothing leaves the machine) or a trusted cloud instance that meets professional-conduct confidentiality requirements.
  • API keys: never hard-code in macros. Always use environment variables or the Credential Manager.
  • Macro signing: sign VBA macros digitally so Office runs them without warnings and updates don't silently activate them.
  • Audit: keep a local log of requests, required for later traceability.

* The processing of confidential content is subject to professional-conduct confidentiality requirements, among others. These can be met by a locally hosted model or, on a case-by-case basis, by a trusted or self-hosted cloud instance. This does not constitute legal advice.

Content partially AI-generated, curated by Sebastian Goebel. This is not legal advice but training material for my workshops. No guarantee of accuracy or completeness. No liability. Software provided as-is.