I need to run a VBA file located on a network drive in Alteryx server. The output from the file. There are formula based on the data, and we want the formula to be refreshed in excel as well. Openpyxl does not does that.
Currently, we have to manually open the file and then save it, so that excel formulas are refreshed. We want to automate it
I have tried
1. Python Tool - I have used Xlwings and win32com.client. Both of them works on Alteryx designer, but they do not work on Server.
a. win32com.client
import win32com.client
def execute_vba_macro(file_path, macro_name):
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
workbook = excel.Workbooks.Open(file_path)
excel.Application.Run(macro_name)
workbook.Close(SaveChanges=True)
excel.Quit()
b. xlwings
import xlwings as xw
def execute_vba_macro():
workbook = xw.Book('your_excel_file.xlsm') # Make sure the file path is correct
workbook.macro('YourMacroName')() # Replace 'YourMacroName' with the actual macro name
workbook.save()
workbook.close()
execute_vba_macro()
2. RunCommand and .bat file - It is working on Designer but again fails on server and does not execute the CMD and keeps the workflow running for indefinite time.
@echo off
set filePath="C:\Path\To\YourWorkbook.xlsm"
set macroName="MyMacro"
REM Start Excel and run macro
start excel.exe /e %filePath% /macro %macroName%
Is there any way we can make the formula refresh in Excel files as well after Output?
Your options are as you state, to either use Run Command/Python Tool/R Tool. There is no native alteryx function that will open the workbook and refresh the formulas.
There is a possiblity that your server is locked down for certain tools, and so that's why it's not working, but that depends on the error message and I think would be clearly stated.
What's happening when you try and run it on the server? Are you getting an error message, or just the formulas aren't updated?
Often a server may not have the required installs to open Excel workbooks, and so possibly those functions are not executing...
Without more info, I am not sure why it's not working, but I don't think you'll find a working option without first figuring out why they don't work, so I would concentrate on that. It could be the user the app is running as, or the location being temporary until the workflow completes. I would put some tracking on the workflow so that you can get more details of each operation and then test to see why those options are not working.
Hey @omkaraditya02, on latest versions of AYX server and MS server the options to open an "non-interactive session" of excel are limited. I recently ran into the same issue where scripts stopped working after upgrades. The problem is that when your flow and script run scheduled, it is the service account operating excel, which is seen as non-interactive. We worked around it (talk to IT about this) by making the service account being seen as an external user, thereby fooling both MS and AYX server and allowing scheduled interaction with excel. Other things to keep in mind looking at your code; keep in mind that excel might already be open on the server, in which case your code is not able to open it.
We run the refresh in python, you may want to use and edit this and let us know how it worked for you:
from ayx import Package
Package.installPackages(['pypiwin32'])
import win32com.client as win32
import os
import time
import pythoncom
# === CONFIGURATION ===
FILE_PATH = r"D:\TEMP\test.xlsx" # Input file (source)
OUTPUT_PATH = r"D:\TEMP\test_refreshed.xlsx" # Output file (after refresh)
VISIBLE = False # True = Excel visible (debug), False = hidden
WAIT_TIMEOUT = 300 # Max wait time in seconds (here: 5 minutes)
POLL_INTERVAL = 5 # How often to check Excel availability (in seconds)
# ======================
def get_excel_instance():
"""
Get an Excel Application instance.
If Excel is already running, attach to it.
If not, create a new instance.
"""
try:
excel = win32.GetActiveObject("Excel.Application")
print("📎 Attached to existing Excel instance.")
except Exception:
excel = win32.gencache.EnsureDispatch("Excel.Application")
print("🆕 Started new Excel instance.")
return excel
def wait_for_excel_idle(excel, timeout: int = WAIT_TIMEOUT, poll_interval: int = POLL_INTERVAL):
"""
Wait until Excel is idle (not calculating or busy).
"""
waited = 0
while True:
try:
# This call will fail if Excel is busy with a modal dialog / long calc
_ = excel.Ready
if excel.Ready:
return True
except Exception:
pass
if waited >= timeout:
print("⚠️ Timeout: Excel is still busy.")
return False
print("⏳ Waiting for Excel to become available...")
time.sleep(poll_interval)
waited += poll_interval
def refresh_excel(file_path: str, output_path: str, visible: bool = False):
"""Open Excel (existing or new), refresh workbook, save under new name."""
if not os.path.isfile(file_path):
raise FileNotFoundError(f"File not found: {file_path}")
excel = None
wb = None
try:
pythoncom.CoInitialize() # Ensure COM initialized for this thread
excel = get_excel_instance()
excel.Visible = visible
excel.DisplayAlerts = False
if not wait_for_excel_idle(excel):
raise RuntimeError("Excel was busy too long. Script aborted.")
# Open workbook
wb = excel.Workbooks.Open(file_path)
# Refresh connections
connection_count = wb.Connections.Count
print(f"🔄 Connections found: {connection_count}")
for i in range(1, connection_count + 1):
conn = wb.Connections.Item(i)
try:
print(f"Refreshing: {conn.Name}")
conn.Refresh()
except Exception as e:
print(f"❌ Could not refresh {conn.Name}: {e}")
excel.CalculateUntilAsyncQueriesDone()
# Save as new file
wb.SaveAs(output_path)
print(f"✅ File saved as: {output_path}")
except Exception as e:
print(f"❌ Error: {e}")
finally:
if wb:
wb.Close(SaveChanges=False)
wb = None
if excel and not VISIBLE:
excel.Quit()
excel = None
pythoncom.CoUninitialize()
if __name__ == "__main__":
refresh_excel(FILE_PATH, OUTPUT_PATH, visible=VISIBLE)
The workflow just goes on an infinite loop as it executes and there is no update till hours when I use run command tool or python tool to excute .bat file.
When I use the same to access Excel, it throws the error that "Excel application is not defined".
Server can’t launch Excel GUI, which is why your VBA macros don’t run. Automating formula refresh might require moving logic to Power Query, Python, or Alteryx formulas instead of relying on Excel macros.
Like @WirkKarl said, the server does not let you define Excel without a interactive session (GUI operated by user). That's why you get the error "Excel application is not defined", Like I said earlier, talk to IT. FYI both MS and AYX advise against this.