0% found this document useful (0 votes)
15 views6 pages

Using Python From Excel Via VBA. This Post Is Based in A Video by Sigma

Uploaded by

David
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views6 pages

Using Python From Excel Via VBA. This Post Is Based in A Video by Sigma

Uploaded by

David
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

22/06/2024 10:18 Using Python From Excel via VBA.

rom Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium

Using Python From Excel via VBA

This post is based in a video by Sigma Coding plus a few posts I found in
Stackoverflow (but lost) to make my code workable.

The point of using python to automate task in Excel, instead of using VBA, is
that in my personal opinion python (and its respective libraries for data
analysis) is a lot easier to write, read and learn, while at the same time being
faster. As a personal experience, once I tried looping around 9k rows with VBA
to modify some values based in a condition, needless to say Excel froze. While in
in Python (with Pandas or Numpy) vectorized operations make looping
complete unnecessary, and even undesirable.

In summary, the reasons to use python instead of VBA to process data:

Faster

More versatile (From text mining to ML)

More resources on the internet to learn and find solutions to the problems
we want to solve.

Easier to write and read

The structure will have 3 parts:

1. Create a subroutinein VBA that runs any python script

2. Run said script that takes as input the data from excel

3. Write the output from the script in the same workbook

https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 2/7
22/06/2024 10:18 Using Python From Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium

I’ll focus on the fist and third part because whatever you want python to do
depends on what you need.

Structure of the code


1. Create a subroutine in VBA that runs any python script

First, we declare the variable needed for the subroutineto run the script, namely
the object shell, folder paths and the command used by the object shell.

Sub run_python_script()
'Declare variables
Dim objShell As Object
Dim python_exe, script_path, folder_path As String
Dim script_name, str_command As String

'Create new shell object


Set objShell = VBA.CreateObject("Wscript.Shell")

Now, we have to provide the shell the command to run python and the file it’ll
run as a text string. First, we provide the location of the python executable
wherever we have python installed in our computer

'Provide the file path to the python exe


python_exe= """C:\Users\USER\XXXXXX\XXXXXX\Python38-32\python.exe"""

Supposing the script is in the same location as the excel workbook we get the
workbook location and add the script name to the path

'Provide the file path to python script


folder_path= Application.ThisWorkbook.Path

https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 3/7
22/06/2024 10:18 Using Python From Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium
script_name = "script.py"
script_path = """" & folder_path & "\" & script_name & """"

And we concatenate both strings with the python executable location and the
script location so it ca be passed to the object shell to run the instruction.

str_command = python_exe & script_path


'Run the python script
ChDir folder_path
objShell.Run str_command

This last line will open the object shell and run our command.

2. Run said script that takes as input the data from excel

This is a simple illustrative code where I’ll use a flight route data set available in
Kaggle (9 columns and 67664 rows) and we’ll do a simple pivot table that will
show the top 10 airports with the most connecting flights.

The data set header looks like this:

The code that creates the process the data and creates the final summary tables
is the folllowing:

https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 4/7
22/06/2024 10:18 Using Python From Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium

We get this output:

3. Write the output from the script in the same Excel workbook

https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 5/7
22/06/2024 10:18 Using Python From Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium

For this we are going to use the win32com library, that allows us to interact with
windows objects from python using VBA code. Not in the best possible way but
it’s one of the few options we have.

It’s important to mention that we need to use the command


ExcelApp.Workbooks.Open(filepath) since we are working with an Excel file
that is currently open.

When we specify the cell ranges and assign the values to those ranges we used
VBA code from our python script:
https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 6/7
22/06/2024 10:18 Using Python From Excel via VBA. This post is based in a video by Sigma… | by Paul Rivera | Medium

In line17 and 19 we used VBA code to specify the ranges where the headers
and data will be pasted in excel respectively.

Line 25: All NaN values should be replaced with apostrophe before writing
the values in excel.

Line 26 and 27: Before writing the panda data frame to the excel range we
need to convert it to a list of records, otherwise we’ll get an error so those
two lines are necessary before writing the values into the excel range in line
28.

Now that we are all set, I hope this small guide helps you to automate at least
part of your repetitive work with excel. If there are some errors in the code
above I’ll appreciate your feedback.

https://medium.com/@paul90.hn/using-python-from-excel-via-vba-fe76d5e53493 7/7

You might also like