how to execute vba macro outside of excel - python

I have an excel spreadsheet with a massive amount of VBA and macros that include a button.
How do I execute VBA code in Excel (specifically to clicking the button and trigger its onclick event) outside excel from python (for example)?
Note: I'm willing to take answers in different languages like C++, C#, or Java; but, by far I would prefer them in python since it'll more smoothly connect with the remainder of my python applications.
Note 2: I may need to manipulate the excel spreadsheet with python using one of the python excel libraries available
Version Numbers:
Microsoft Excel Office 365 Version 1708 Build 8431.2079
python 2.7

You can use the win32com library to interact with COM Objects through Python. You can to install the win32com library with pip. That's how I did it at least. Essentially, you are not clicking the button on your worksheet, but instead calling the subroutine embedded in your VBA code to run on your worksheet.
Also, I used Python 3.6 for this, but I believe Python 2.7 should be compatible. Here is a basic outline.
Install Win32Com
Open up and command prompt and type:
pip install pypiwin32
Code
import win32com.client as win32
excel = win32.Dispatch("Excel.Application") # create an instance of Excel
#excel.Visible = 1 #Uncomment this to show Excel working through the code
book = excel.Workbooks.Open(Filename=r'C:\YourBookHere.xlsm')
excel.Run("YourBookHere.xlsm!Sheet1.MacroName") # This runs the macro that is on Sheet1
book.Save()
book.Close()
excel.Quit()
Hope this helps, this is my first post.
Edit: Cleaned up things a bit

To expand upon dylan's excellent answer: you can also accomplish the same using the python xlwings package. In essence xlwings is a fancy wrapper around pywin32 that allows control of an excel application with even simpler syntax. The following python code should do the same as the code from dylan's answer:
import xlwings as xw
# Connect to existing workbook containing VBA macro
wb = xw.Book(r'C:\YourBookHere.xlsm')
# Run the VBA macro named 'MacroName'
wb.macro('MacroName')()

In addition, you can also use Windows Task Scheduler to fire the event. If a button-click-event fires the code, you can do exactly the same thing, by following the instructions in the link below.
https://www.sevenforums.com/tutorials/11949-elevated-program-shortcut-without-uac-prompt-create.html
Also, you will need a Workbook-open-event, so, something like this...
Private Sub Workbook_Open()
Msgbox "Welcome to ANALYSIS TABS"
End Sub

Related

Manage and import libraries in python installed in libreoffice

I am sorry if this question has already been answered, however it is a topic very little discussed about.
I am trying to run a macro in libreoffice. The macro has been written in python as shown.
import uno, os.path, sys
import pandas
def Bring_from_doc():
doc = XSCRIPTCONTEXT.getDocument()
siz=doc.Sheets
uno, os and sys can be imported without any issue since they are installed in libreoffice python installed folder.
However pandas is not installed and got this error when running script:
This is the directory where libreoffice python libraries are located including uno, os and sys. But pandas and other wanted are not.
My question is: How can be installed pandas and any other required library that can be used by any python script run by libreoffice in a macro?
Thank you!!
On Linux, this is easy. Simply install the library in the system python and it will work from a LibreOffice macro. Verify whether it is python 2 or 3 on your system; for example on Ubuntu, normally I enter python3 as the executable name.
On Windows, this is nearly impossible and I would not recommend it (and have repeatedly stated this on stackoverflow, as it is asked here every so often). Numerous environmental variables must be set correctly and other hacks are required. If you are an expert then it can be done, but since you are asking here, my guess is that you do not have the required skills to make this process go smoothly!
Even if you do get it to work, no one else will be able to use your macro, and you would need to do it all over again if you use a different computer. So I would not recommend it in most cases even for experts.
Alternatives:
Run Linux in a virtual machine.
Install a normal distribution of python elsewhere on your system, and write a normal python script that imports pandas, saving the result for example to an xml file. When that script is finished, run a LibreOffice macro that reads the result file and does not import pandas.
Avoid using specialized libraries at all. This is what I normally do, as the standard python libraries allow you to do quite a bit, maybe not as easily, but you could import some extra code or write workarounds to do what is needed.

How can I use the Python language to put add-ins in Excel without using Pyxll or xlwings or VBA?

I am trying to figure out how to use Python-based functions in excel. I came across Pyxll which can make Python add-ins instead of using VBA. But Pyxll is not free after their 30-day trial.
I also came across xlwings which worked fine and served the purpose of adding udfs in excel, the problem is--- it is not very user-friendly. I have to put the excel file in the same folder as the python file plus, they should also have the same names with different extensions. Or I may use the xlwings quickstart command to do that.
This means I have to create such folders everytime I wish to include my python based functions in a new excel project file and copy paste the functions from the previous python files to the newly created quickstart files.
I was wondering if there is any way to use only one python file to import user-defined functions using xlwings or perhaps a different library/module which is free to use and does that?
(PS: According to the xlwings documentation, we can point to a udf module under the xlwings tab in excel but even after many attempts I am not able to make it work )

Differences between xlwings vs openpyxl Reading Excel Workbooks

I've mostly only used xlwings to open (read-write) workbooks (since the workbooks I read have complicated macros). But I've recently begun using openpyxl to open (read-only) workbooks when I've needed to read thousands of workbooks to scrape some data.
I've noticed that there is a considerable difference between how xlwings and openpyxl read workbooks. I believe xlwings relies on pywin32 to read workbooks. When you read a workbook with xlwings.Book(<filename>) the actual workbook opens up. I have a feeling this is a result of pywin32.
However, when using openpyxl.load_workbook(<filename>) a workbook window does not appear. I have a feeling this is a result of not using pywin32.
Beyond this, I've no further understanding how the backends work for each libraries. Could someone shine some light on this? Is there a benefit/cost to relying on xlwings and pywin32 for reading workbooks, as opposed to openpyxl which does not seem to use pywin32?
You are correct in that xlwings relies on pywin32, whereas openpyxl does not.
openpyxl
A ".xlsx" excel file is essentially a zip-file containing multiple XML files formatted according to Microsoft's OOXML specification. With this specification it's possible to create a program capable of directly reading/writing excel files in just about any programming language. This is the approach applied in openpyxl: it uses python code to read/write excel files directly.
xlwings
A Microsoft Excel application can be started and controlled by an external program through the Win32 COM API. The pywin32 package provides an interface between Win32 COM and Python. Through a python script with the right pywin32 commands you can fully control an Excel Application (open excel files, query data from cells, write data to cells, save excel files, etc.). The pywin32 commands that you can use mirror the Excel VBA commands, albeit with python syntax.
xlwings is (among other things) a user-friendly wrapper around pywin32. It introduces several concise-yet-powerful methods. An example would be the methods for direct conversion of an excel cell range to a numpy array or pandas dataframe (and vice versa).
Summary
A fundamental difference between xlwings and openpyxl is that the former requires that MS Excel is installed on your machine, whereas the latter does not.

How to edit Excel(.xlsx) documents using python - but without using any non-standard modules?

Is there a way to edit an Excel document in python without using any modules that are made to work with Excel documents? I'm not looking for external libraries, I'd like to learn about how to do it on my own.
My goal is to make a program that will scan my progress in my online classes, and update the .xlsx accordingly.
If by "modules that are[] automatically included in python" you mean those that are included in a major distribution of Python, several modules that work with Excel are included in the Anaconda distribution. Many of these, such as xlwings and xlsxwriter, are automatically installed with Anaconda, while some others require a simple conda install.
A list of Anaconda modules more specific to Excel is here.

Can I integrate Datanitro into an executable?

I'm looking to be able to create an executable with py2exe or something similar that takes information from an excel sheet and returns a word file.
Since my coworkers are technically challenged, I need to create an executable that will take the work out of it for them.
Two questions here:
I have to be able to import something into the python script that represents DataNitro. What module represents DataNitro?
Is this legal? I won't be using a DataNitro license on every machine this exe will run on, besides my own, so if it's even possible, is this a bit shady?
Thank you.
P.S. If I'm not able to do this I will probably have to use xlrd,xlwt,etc.
The best way to give non-technical users access to DataNitro is to copy the VBA interface: hook the script up to an Excel button and have users press that button to run it. (There's no difference between running a Python script with DataNitro and running VBA code from the user's point of view.)
Each person using the script would need a DataNitro license.
There's no way to make DataNitro work with py2exe, unfortunately.
Source: I'm one of the DataNitro developers.

Categories

Resources