gyetvaig

Run VBA from Python

May 19th, 2019
908
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. import os
  2. import win32com.client as win32
  3.  
  4.  
  5. def run_excel_macro (file_path, separator_char):
  6.     """
  7.    Execute an Excel macro
  8.    :param file_path: path to the Excel file holding the macro
  9.    :param separator_char: the character used by the operating system to separate pathname components
  10.    :return: None
  11.    """
  12.     xl = win32.Dispatch('Excel.Application')
  13.  
  14.     try:
  15.         wb = xl.Workbooks.Open(os.path.abspath(file_path))
  16.         xl.Application.run(file_path.split(sep=separator_char)[-1] + "!main.simpleMain")
  17.         wb.Save()
  18.         wb.Close()
  19.  
  20.     except Exception as ex:
  21.         template = "An exception of type {0} occurred. Arguments:\n{1!r}"
  22.         message = template.format(type(ex).__name__, ex.args)
  23.         print(message)
  24.  
  25.     xl.Application.Quit()
  26.     del xl
  27.  
  28. separator_char = os.sep
  29. run_excel_macro(input('Please enter Excel macro file path: '), separator_char)
Advertisement
Add Comment
Please, Sign In to add comment