The Run member of the Range object in the Excel object model is accessible via xlwings and is used to execute a macro or a user-defined function (UDF) that is associated with a specific range. This is particularly useful for running custom VBA code that is tied to a worksheet event or a specific cell action. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model.
Functionality:
The primary function of Range.Run is to execute a macro or function. It can be used to trigger VBA procedures that are defined in the workbook. This allows for automation and integration of custom business logic directly from Python scripts using xlwings.
Syntax:
In xlwings, the syntax for calling the Run method on a Range object is:
range_object.api.Run(Arg1, Arg2, ..., Arg30)
range_object: This is the xlwings Range object representing the cell or range in Excel.Arg1, Arg2, ..., Arg30: These are optional arguments that can be passed to the macro or function being executed. They correspond to the parameters expected by the VBA procedure. You can pass up to 30 arguments, mirroring Excel’s VBA capabilities.
The arguments are passed by value, and their types should match what the VBA code expects (e.g., strings, numbers). If no arguments are needed, you can call the method without any.
Example:
Suppose you have an Excel workbook with a VBA macro named ProcessData that takes two arguments: a string for a report name and a number for a threshold. The macro is designed to process data in a specific range. Using xlwings, you can execute this macro from Python.
First, ensure the workbook is open and connected via xlwings. Then, you can use the following code:
import xlwings as xw
# Connect to the active workbook or open a specific one
wb = xw.books.active # Assumes Excel is running and workbook is open
ws = wb.sheets['Sheet1']
# Define the range where the macro is associated (if applicable) or any range
target_range = ws.range('A1')
# Execute the macro with arguments
target_range.api.Run("ProcessData", "MonthlyReport", 100)
Leave a Reply