I'm writing a Python script to automate a process that uses Excel macros to format files to input into a different program later on. I'm a bit new to Python and completely new to VBA, but I think I have the steps down.
So far I have this to run the macro itself (with help from other SO posts):
xl = win32com.client.DispatchEx('Excel.Application')
xlpath = os.path.expanduser(xlfile)
wb = xl.Workbooks.Open(Filename=xlpath, ReadOnly=1)
xl.Run("my_macro")
At this point the macro runs and calls Application.GetOpenFilename() to open a dialog for the user to choose the file to be formatted, which is going to be different for each macro.
Basically my user is going to have different initial data to format each time they run my script. At the beginning I want them to choose the files that they need formatted and then I'll save those file paths. Then I want to plug those file paths into the macro from Python instead of opening the dialog in Excel.
Is there a way to do this directly by changing the macro? If not, will I need to rewrite the macro in Python with one of the modules out there for driving Excel?
It looks like I can call xl.Run("my_macro") with parameters so I just have to figure out how the macro reads in those parameters so once I pass in the paths it can just open the files without the dialog.
xl.Run("my_macro", path1, path2)
https://stackoverflow.com/a/16740500/3788802
Related
The idea is to create n CAD models as per the sampling algorithm, each of those n CAD models are saved in separate directories along with a equations.txt file and a Macro.swp file.
So, I am writing a loop in python that
a) goes to each directory
b) updates the equations.txt file taking values from the sampling algorithm output.
c) run a batch file that (opens solidworks, builds the model after the equations.txt update, saves sldprt)
Now, in c), the steps of opening building and saving a sldprt are in macro.swp file, which has a path mentioned in it to open the CAd file. As I have n directories, I need to be able to update this path for each macro.swp file as well.
Unfortunately macro.swp does not open as a text file to be updated by python.
I tried changing the extension from swp to bas, which is text format, but then the extension cannot be changed back to swp, making it impossible to update the path in the macro as a text update.
Can anyone suggest, how can I change the path in the macro file?
SolidWorks macros can be save as text files with SWB extension.
But I think a better solution would be to get the folder of the current macro with GetCurrentMacroPathName. And eventually get the cad files path from either the current directory with GetFolder or from the equations.txt
I'm trying to automate some things with python, one of the steps is opening the .xlsx file using the "win32com.client" module and then printing a few sheets into PDF.
It all works fine if I have the file already opened in Excel, but if the Python script wants to open it, Excel asks me to set a different name for "_FilterDatabase" and "Print_Area", even though I can open it manually with no issues.
If I do change the names, then I have to set all the print areas again. Saving the file with new print areas causes the same issue. I don't have any idea why opening the file with win32com is different than opening it manually.
Here's the simple code, just for opening the file:
import win32com.client
wb_path = r'D:\Users\Agenerick\Documents\Projects\sprawozdania-gen\excel\a.xlsx'
o = win32com.client.Dispatch("Excel.Application")
o.Visible = True
o.Workbooks.Open(wb_path)
I've tried using the ReadOnly flag and xlwings, even using ComObject in Powershell, no difference, however, opening the file using subprocess went fine, but then I can't really hide the window. I also don't have any other versions of Excel installed.
Friend helped me with it and found a post in German with a similar bug. The way I fixed it is I replaced o.Workbooks.Open(wb_path) with o.Workbooks.OpenXML(wb_path)
Apparently it's a bug with Excel. After that I also had to change wb.Worksheets.Select() (or something similar) to wb.Sheets.Select()
Is there any way to run in Pyhton the equivalent of this Excel VBA code:
For i= 1 to 10
'do some stuff
'Refresh calculations in order to check the outcome
Next i
In other words: is it possible to refresh sheet formula results from within python, then rinse and repeat ? I tried saving as excel file and re-opening after each iteration, but it is too time consuming to begin with.
You can run VBA without Excel. Just save the code into a file and use the windows built in command vbscript.
https://www.faqforge.com/windows/run-vbscript-windows/
You can run the command via subprocess.
If you want to run code in Excel, you have to write an Excel addon in python.
There is an open source library called xlwings: https://www.xlwings.org/
(there is also a premium version of xlwings but you do not need them)
I've got some Python code that runs a query on a database that is read-only from my end and, which dumps me an Excel spreadsheet with relevant data that I want for visualization. I have several macros which process the data, create and edit graphs, and let me "filter" a couple different ways (each "filter" is several normal filters - convenient compared to manually selecting/clearing multiple filters).
My Python code generates a new Excel file daily stamped with the date. I would like to insert my suite of macros and run the setup ones automatically on each new file, rather than manually importing and executing them.
Is there a way to use a macro to insert several other macros, run some of them, and insert macro buttons or a dropdown box to run the filtering bit? If not, can it be done (or should it be done) from the Python side when it generates my Excel files?
Edit:
The python code was written by somebody else, and I do not know Python. It prints the data using:
with pd.ExcelWriter(filename) as writer:
df_merged_final.to_excel(writer, sheet_name='Final Data', index=False)
You can collect all your macros in a .bas file and import that whenever needed.
1) collect all your regular macros and put them in a module. You can even write one parent macro that calls all the other child macros, but they all need to be in this module;
2) export the module as a .bas file;
Then whenever you need the macros:
3) import the .bas file to your workbook;
4) your macros are now available in the ribbon of the developer tab which presents them as a dropdown list. If you used a parent macro, you can just click the parent macro to fire all the child macros.
This allows you to work in the source file itself and you can avoid copying large amounts of data to the clipboard. Also serves as a great backup of your most-used macros in case your master Excel file becomes corrupt.
I have a viewer I built using WXPython. The viewer is basically a browser (built on IE wx.lib.iewin) that loads the txt or htm files I have in a directory and then lets me move through the files sequentially. Instead of having to go to the directory to select the next file to view the viewer/browser has a next button that loads the next file in the queue.
I want to be able to add a new feature that allows me to highlight some text that is visible in the browser and then push a button and have that text passed into a cell in excel.
Lots of things are going to have to happen like I need to be able to find and start a new instance of excel. I need to be able to add a new worksheet and pass some values to populate cells on the worksheet based on the file I am looking at and then if I want to collect some data from the file I want to be able to highlight the data in the viewer and then press a button on the viewer and have the data passed to excel.
I think I am going to start with PyWin32 but I am wondering if there is something else I need but I don't know enough to look for it.
If someone knows of an example where text was piped from a Python application to excel under the users control I would appreciate a pointer in that direction. It is easy enough I think to do this going from the application to a file that gets created (but not displayed) but I am hoping to go from the browser to the excel file so that the user can evaluate their work in progress.
I'd recomend using one of the python excel modules like python-excel.
It works on any OS, and without any other Excel application installed.
http://www.python-excel.org/
Code would look somehting liek this to write to a new xls document, slightly different to open an existing.
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
# indexing is zero based, row then column
sheet.write(0,1,'test text')
wbk.save('test.xls')
Hopefully this can get you on the right path, then you'll be able to post more specific questions if you run into problems.
Note: Another option is openpyxl:
http://packages.python.org/openpyxl/tutorial.html
If you're using wxPython (which I assume you are due to the tag), you should look at XLSGrid: http://www.blog.pythonlibrary.org/2011/08/20/wxpython-new-widget-announced-xlsgrid/
If you just want to work with Excel, I would recommend xlwt or xlrd, although you can use PyWin32 to work with it too via COM: http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/