Search code examples
pythonexcelvbaopenpyxl

Extract VBA as TXT from XLSM with Python


I want to extract the VBA code from an .xlsm file and save it as .txt files. Unfortunately, I get only .bin files when I unzip the .xlsm file which I cannot open with an editor.


Solution

  • You can use olevba :

    #pip install oletools
    import oletools.olevba as olevba
    
    vba = olevba.VBA_Parser("file.xlsm")
    
    with open("output.txt", "w") as f:
        for *_, n, m in vba.extract_all_macros():
            if n.startswith("Module"):
                print(m, file=f)
    

    NB : If you want to target the Excel objects as well, you can use this approach.

    Output (output.txt) :

    Attribute VB_Name = "Module1"
    Sub Foo()
    
        Range("B1").Select
        ActiveCell.FormulaR1C1 = "StackOverflow"
        Range("B2").Select
        
    End Sub
    

    Input used (file.xlsm) with this code :

    enter image description here