Saturday, 10 February 2018

Run a macro using XLwings

Sometimes in life there are things that you cannot achieve in Excel using XLwings, shocking I know. The 2 examples that I have found so far are password protecting a file and changing the file type e.g. from xlsx to xlsm, these might be possible but I cannot get them to work. For a while I could not get pivots to refresh but as I have covered before that can be done. 

The 2 examples I have given above can easily be achieved using a macro (I may cover these elsewhere). But what this means is you can use XLwings to run the macro and you still have everything being done in a single script. The below gif and code show this. In this example my very simple code just shows a bunch of rows in column B being set to Y. 


The code:


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 08:58:53 2018
@author: garym
"""
import xlwings as xw
import time
### open workbook
wb = xw.Book(r'C:\Users\garym\Documents\PyWinAutoBlog\AutoAutoBlog\Macro.xlsm')
time.sleep(5)
### Run the Macro
ExcelMacro = wb.macro('Macro1')
ExcelMacro()
time.sleep(5)
## Close the workbook
wb.close()

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. hi, I tried to use your code on a Mac and I got the following error: from appscript import app, mactypes
    ModuleNotFoundError: No module named 'appscript'; do you have any suggestion?

    ReplyDelete