#3178 Excel VBA Ollama Script
#3178 Excel VBA Ollama Script
#3178 Can my Chrome browser execute a pyhon application on my PC without a server?
Short answer—sort-of, but with caveats
Chrome (or any modern browser) can interpret Python entirely inside the page, but it cannot launch a “normal” desktop Python script that has unrestricted access to your PC unless you give it help (e.g., via a helper app, local server, or extension).
Below are the practical ways to do it, what each can and can’t do, and when they make sense.
1. In-browser Python via WebAssembly
| Technique | How it works | What you gain | Key limits |
|---|---|---|---|
| Pyodide / PyScript | CPython 3.x compiled to WebAssembly is downloaded with the page, runs in the browser sandbox. You embed <script type="py"> … </script> or call pyodide.runPython(…). | No installation for the user, runs offline after first load, can call most Python libraries that are pure C/Python (NumPy, pandas, scikit-learn already work). | Sandbox: no raw disk, no direct sockets, no shell, heavy download (~5–15 MB compressed). |
| Brython, Skulpt, Transcrypt | Transpile Python to JavaScript. | Tiny payload, simple for teaching or UI glue. | Only a Python subset; no NumPy/SciPy; same sandbox as JS. |
When to use it
-
Educational notebooks, data-vis dashboards, little AI demos.
-
Anything where browser-sandboxed file I/O (IndexedDB, fetch) is enough.
2. Chrome extension + Native Messaging host
-
You package a Chrome extension (HTML/JS UI).
-
You register a native-messaging host—a small JSON manifest that points to
my_script.pyon the PC. -
The extension can send/receive JSON to that script over stdin/stdout.
Pros
-
Script runs with full OS privileges (read files, open sockets, call DLLs).
-
No “server” process to start manually; Chrome launches it on demand.
Cons
-
User must install both the extension and the native host (one-time OS-level install).
-
Only JSON messages—no raw pipes, limited 4 MiB per message.
-
Cross-platform packaging work.
Useful for tight integrations (e.g., automate CAD, open local files, control hardware) without an HTTP server.
3. Local helper app exposing a custom protocol
-
You ship a tiny Python (or Go/Rust) app that registers a custom URL scheme (
myapp://), or listens onlocalhostonly. -
Chrome navigates to that scheme or makes
fetch("http://127.0.0.1:port/...").
You said “without a server,” but a loopback-only helper is often the simplest secure path. Because it never leaves the machine, firewall rules are minimal and latency is nil.
4. Progressive Web App (PWA) that bundles Pyodide
If you want an “installable” feel: wrap a PyScript page as a PWA. Chrome lets users “install” it; afterwards it runs offline, still sandboxed.
What Chrome cannot do natively
-
Launch an arbitrary
.pyfile on the file system by double-clicking a link. -
Grant raw filesystem or network access to in-page code beyond the Web APIs (unless the user explicitly picks a file via the File System Access API, which still gives you a sandboxed handle).
-
Bypass OS security—the browser sandbox is intentional.
Choosing an approach
| Need | Best option |
|---|---|
| Quick interactive demo, heavy numeric libs | Pyodide / PyScript |
| Teaching beginners, tiny footprint | Brython / Skulpt |
| Full OS access with no visible server window | Chrome extension + Native Messaging |
| Stand-alone desktop+web bundle | Electron or Tauri using a built-in Python runtime |
| Occasional automation on your own PC (no redistribution) | Just run the script in a terminal or VS Code—simplest of all |
Opportunity for improvement (your innovation lens)
-
Build a “Pyodide-lite” loader that lazy-streams only the parts of the standard library actually used, cutting first-load size for spot demos.
-
Create a no-code packager: drag-and-drop a
.pyfile and get a signed Chrome extension + native host installer, lowering the barrier for non-developers. -
Offer a browser-first plugin framework where backend code is written once as standard Python but is auto-compiled to WebAssembly or registered as a native host depending on required permissions—letting the same code run in-sandbox or “break out” when needed.
Bottom line:
Yes, Chrome can run Python through WebAssembly today, and you can get full-privilege Python by pairing Chrome with a native host. What it cannot do is magically execute arbitrary local scripts out of the box—sandbox and user consent rules still apply. Pick the path that matches the level of OS access you truly need.
How do I activate VBA in excel?
Below are the two things most people mean when they ask to “activate VBA in Excel.”
Follow each section in order and you’ll be ready to record, write, and run macros.
1 Add the Developer tab (the gateway to VBA)
| Excel on Windows (365 / 2016-2021) | Excel on macOS (365 / 2019-2021) |
|---|---|
| 1. File ▸ Options ↳ Customize Ribbon | 1. Excel ▸ Preferences ↳ Ribbon & Toolbar |
| 2. In Main Tabs, tick Developer. | 2. In the right-hand list, tick Developer. |
| 3. Click OK. You now have a Developer tab on the ribbon. | 3. Click Save. The Developer tab appears. |
One-time action; Excel remembers the setting.
2 Make sure VBA macros are allowed
-
File ▸ Options ▸ Trust Center ▸ Trust Center Settings ▸ Macro Settings
-
Pick one of these (you can tighten it later):
-
Disable all macros with notification – safest everyday choice; Excel shows an Enable Content button when you open a workbook that contains code.
-
Enable VBA macros – only if you trust every file you open.
-
Security tip: Never enable macros globally if you routinely open files from email or the web; use the “notification” option instead.
Opening the Visual Basic Editor
-
Press Alt + F11 (Windows) or ⌥ Fn F11 / Option + F11 (Mac).
-
Or click Developer ▸ Visual Basic.
Inside the editor you can:
-
Insert ▸ Module – write or paste standard VBA code.
-
Insert ▸ UserForm – design a form.
-
Run ▸ Run Sub/UserForm (or F5) – execute.
Saving workbooks that contain code
-
File ▸ Save As ▸ Save as type: Excel Macro-Enabled Workbook (.xlsm)
(On Mac: File Format: Excel Macro-Enabled Workbook).
Excel blocks VBA if you store the file as plain .xlsx.
Quick troubleshooting checklist
| Symptom | Fix |
|---|---|
| Developer tab missing again | Check that you saved Excel settings (some corporate PC images reset options at login). |
| Macros still disabled | Trust Center → Macro Settings may be overridden by Group Policy; contact IT. |
| Alt+F11 does nothing | The keyboard shortcut can be intercepted by add-ins; try the ribbon button. |
| “Can’t find project or library” | Open VB Editor → Tools ▸ References → locate the missing library or un-tick it. |
Where to go next
-
Record Macro (Developer tab) – watch Excel generate VBA as you work and study the code.
-
Office VBA reference (Microsoft Learn) – full object model docs.
-
Immediate Window (Ctrl+G in the VB Editor) – quick one-line experiments.
Once the Developer tab is visible and macros are enabled, VBA is fully “activated” on your installation—no extra components or server required. Happy automating!
How can I test the following installed VBA script: """...https://www.reddit.com/r/ollama/comments/1d6c62o/excel_and_ollama/..."""?
Below is a practical, step-by-step checklist you can walk through to make sure the TestOllamaCompletion macro actually fires, reaches your local Ollama instance, and prints a response.
1 Confirm the prerequisites
| Requirement | Quick check | Notes |
|---|---|---|
| Ollama running on the same PC | In a terminal run ollama list → you should see wizardlm2:7b with a status of “ready”. | If it isn’t listed, run ollama pull wizardlm2:7b and then ollama serve (or just restart Ollama Desktop). |
| Endpoint reachable | In a browser visit http://localhost:11434 → you should at least get a “404 page not found” (shows port is listening). | Port number must match the client.Open line in your code. |
| JSON-Converter module imported | In the VB Editor, Modules ▸ JsonConverter should exist. | If not, download JsonConverter.bas from VBA-JSON and File ▸ Import File… |
| MSXML available | VB Editor → Tools ▸ References → tick Microsoft XML, v6.0 (or v3/4 if 6 isn’t installed). | If you stay with late binding (CreateObject("MSXML2.ServerXMLHTTP")) this isn’t strictly required, but early binding + compile-time checks are nicer. |
strKey defined (only needed if your Ollama endpoint is protected) | Add Const strKey = "" at the top of the module (or remove the header line entirely for a local, unsecured Ollama). | Empty string is fine for local use; remote endpoints may need a token. |
2 Paste/compile the code
-
Developer tab ▸ Visual Basic
-
Insert → Module → paste the code.
-
Optionally add
Option Explicitat the very top and do Debug ▸ Compile VBA Project.
Fix any red-lines before moving on.
3 Run the test macro
-
Press Ctrl + G to bring up the Immediate window (so you can read
Debug.Print). -
Place the caret anywhere inside
Sub TestOllamaCompletion -
Press F5 (Run) or F8 (step through line-by-line).
If everything is wired correctly you should see something like:
printed in the Immediate window.
4 Typical issues & quick fixes
| Symptom | Likely cause | Fix |
|---|---|---|
Compile error: “User-defined type not defined” on Dictionary | You copied early-binding sample but didn’t reference Microsoft Scripting Runtime. | Either tick the reference or switch back to late binding (CreateObject("Scripting.Dictionary")). |
Run-time error ‘424’: Object required at JsonConverter.ConvertToJson | JsonConverter module missing or misspelled. | Import the module; make sure the Function ConvertToJson is visible. |
Error 9001 “Failed to fetch” (raised from Err.Raise) | Ollama not listening, wrong port, or model hasn’t finished loading. | Verify http://localhost:11434 and that wizardlm2:7b shows “running” in ollama list. |
| Response is empty | Returned JSON structure changed (older Ollama builds) | Inspect client.responseText in the Immediate window; adjust the path completion("message")("content") if the API changed. |
| “Connection refused” | Corporate firewall/AV blocks loopback HTTP. | Temporarily whitelist Excel.exe or switch to HTTPS on a different port. |
5 Optional quality-of-life tweaks
-
Surface the answer in Excel rather than the VB Editor:
-
Wrap network call in
On Error…so Excel doesn’t halt abruptly. -
Use early binding for MSXML (faster, IntelliSense):
-
Parameterise the model so you can A/B test LLMs from the sheet:
Quick test script you can drop in after everything compiles
If that dialog pops up with a sensible LLM reply, your VBA-to-Ollama pipeline is officially working. From there you can wire it into worksheets, buttons, or larger automation flows.
How do I execute the chat from the worksheet?
Below is a compact “cookbook” for wiring the Chat function to a worksheet so you can send a prompt from cells and see the LLM’s reply appear in another cell—no VB Editor window required.
1 Expose Chat as a worksheet function (UDF)
Your code already declares
Because it’s Public and lives in a standard module, Excel will recognise it as a User-Defined Function (UDF).
That means you can simply type a formula such as
in any cell and Excel will call the API and return the string result.
Quick worksheet layout
| Cell | Purpose | Example |
|---|---|---|
| A2 | System / prompt message | You talk like a 1920s gangster. |
| B2 | User message | What's the big idea, pal? |
| C2 | Model name (optional) | wizardlm2:7b |
| D2 | Formula that gets the answer | =Chat(B2, A2, 250, C2) |
Important caveats
-
Excel may re-evaluate the formula frequently (every recalc, on open, etc.), causing repeated API hits.
Mitigation: switch Calculation to Manual (Formulas ▸ Calculation Options) or use the macro approach below. -
If the call throws an error Excel will show
#VALUE!. Wrap the call in a helper that swallows errors if you need a cleaner sheet.
2 Trigger the chat with a button (safer / cleaner)
If you prefer one-click execution (or want to avoid the continuous recalculation issue), wrap the call in a simple macro and bind it to a Form-Control button.
Wire it up
-
Developer ▸ Insert ▸ Button (Form Control)
-
Draw the button on the sheet, choose RunChatFromSheet.
-
Rename the button caption to something like Get Response.
Now the API is only called when you press the button.
3 Automatic refresh when the user edits input cells (optional)
If you like “live” behaviour without explicit buttons but still want to avoid constant recalc, add a Worksheet_Change event:
4 Best-practice tweaks for production use
| Topic | Suggestion |
|---|---|
| Long-running calls | Set Application.ScreenUpdating = False and StatusBar text inside the macro so Excel doesn’t look frozen. |
| Throttling / caching | Store the last prompt+user+model hash in a hidden sheet; skip the call if nothing changed. |
| Asynchronous pattern | For heavy models you can off-load the call to a VBA class that uses DoEvents in a loop, or call a small helper executable and poll; VBA itself has no built-in async/await. |
| Error logging | Write failures and timestamps to a log sheet so you know when the LLM or network misbehaved. |
| Security | Leave strKey empty for localhost; if you expose the endpoint beyond your PC, protect it and never hard-code a real key in a shared workbook. |
Smoke-test in one minute
-
Make sure Ollama is running (
ollama listshows wizardlm2:7b). -
Fill A2/B2 as above.
-
Paste RunChatFromSheet into a module, press F5.
-
Response appears in D2 → success.
That’s all that’s required to “execute the chat from the worksheet.” Feel free to adapt the ranges, add a token counter, or loop over many rows for batch prompting.
I get #NAME? for =Chat(x,y,z)
#NAME? means Excel can’t find a name that you typed.
For a UDF that almost always means Excel doesn’t see the function or it’s trying to interpret the arguments as names instead of values / cell references.
1 Make sure Excel can “see” the Chat function
| Check | How |
|---|---|
| Function lives in a standard module | In the VB-Editor (Alt + F11) the code should be inside Module1, Module2, … – not inside “Sheet1 (Sheet1)” or “ThisWorkbook”. |
Public, no Option Private Module above it | The first few lines of the module should look like:Option Explicit (optional)Public Function Chat( … ) |
| Workbook is macro-enabled and macros are turned on | Save as .xlsm and enable macros when you open it. |
| Compile error-free | VB-Editor ▸ Debug ▸ Compile VBA Project – fix any red lines. |
If any of those fail, Excel treats Chat as an unknown name → #NAME?.
2 Call it with real cell references or quoted text
When you write
Excel thinks x, y, and z are named ranges.
Unless you created names called x, y, and z, the result is #NAME?.
Correct patterns
| Goal | Example formula | Explanation |
|---|---|---|
| Use worksheet cells | =Chat(B2, A2, 250) | B2 = user message, A2 = system prompt, 250 = max tokens |
| Pass literal text | =Chat("What's up?", "You are a pirate.") | Surround strings with quotes |
| Omit optional args | =Chat(B2) | Only user message; prompt uses default |
Remember: Chat(promptMessage, userMessage, maxTokens, model)
3 Quick test checklist
-
In an empty sheet put:
-
A2 →
You talk like a 1920s gangster. -
B2 →
What's the big idea, pal?
-
-
In C2 enter either of these:
-
As a formula using cells
-
Or hard-coded text
-
-
Press Enter.
If Chat is recognised, Excel shows the Ollama reply after a short pause.
If you still see#NAME?, go back to step 1.
4 Other causes (less common)
| Cause | Symptom | Fix |
|---|---|---|
| Workbook open in Protected View | Yellow bar: “Enable Editing” | Click Enable Editing then Enable Content |
Function marked Private | Compiles but not available in sheet | Change to Public Function Chat |
| You renamed the module but left code in a class module | VBE icon looks like a stack of boxes | Move the function to a standard module |
tl;dr
-
#NAME?→ Excel doesn’t recognise Chat or the arguments. -
Ensure the code is in a public standard module, workbook is .xlsm, macros are enabled, and call it with real cell references or quoted strings – not bare letters x, y, z.
How can I add a parameter to chat that is the start of the output range?
What you can (and can’t) do in Excel
| Goal | Works as a worksheet formula? | Works with a macro / button? |
|---|---|---|
| Return a value and let it “spill” into neighbouring cells | Yes (must return a Variant array). Excel itself decides where to put it. | Yes |
| Tell a function which other cell(s) to write to | No – a UDF is forbidden to change anything except the cell that called it. | Yes – a Sub or Function called from VBA (button/menu) can write anywhere, because it runs outside the sheet-calculation sandbox. |
So you have two practical patterns:
1 Keep it a worksheet function → return a spill array
If the only reason you wanted an “output start” argument was to have the reply occupy several cells, just return an array and let Excel spill it.
Usage in the sheet (one formula, automatic spill):
If you prefer columns rather than rows, wrap the result in TRANSPOSE().
2 Let the caller tell VBA where to write → add a Range parameter
Create a wrapper Sub that accepts three ranges: system prompt, user prompt, and outputStart.
Because it runs as a macro (not as a sheet UDF) it can write anywhere.
Two easy ways to trigger it
-
Button on the sheet
-
Insert ▶ Button (Form Control)
-
Assign macro:
-
-
Worksheet event (auto-update when inputs change)
Which option should you choose?
| If you want… | Choose… |
|---|---|
| Simple “fire once” behaviour tied to a button | Option 2 (macro) |
| A formula that recalculates like any other, no buttons | Option 1 (spill-array function) |
| Multiple prompts in a table, one reply per row | Still Option 2 – loop down the table and write beside each row. |
Either way, you don’t pass a “start-cell” argument into Chat itself when calling it from the worksheet; instead you (a) let Excel spill the array automatically or (b) run a wrapper macro that knows where to place the output.
From <https://chatgpt.com/> ChatGPT o3
Comments
Post a Comment