如何把Excel VBA变成git

我在Excel中inheritance了一些VBA,并希望将其放入git中。 就目前来看,git认为它是二进制的,不想做文件改变增量,而是重复整个文件。

我想把个别的macros分解成文件,把它们放到git中。 有没有一个标准的方法来做到这一点?

你应该能够导出模块作为文本到一个混帐文件夹然后提交如下。

在VBA编辑器中为每个macros添加模块(菜单插入/模块)将每个macros代码复制到模块中,并用控制+ E保存为文本文件。保存到git文件夹中并使用正常的git过程来提交任何更改。

当你更改VBA代码重新保存(控制+ E)的模块,并正常更新GIT。

你可以创build一个git pre-commit hook来运行下面的Python脚本来自动提取你的VBA代码并将其添加到你的提交中(参见https://www.xltrail.com/blog/auto-export-vba-commit-hook ):

import os import shutil from oletools.olevba3 import VBA_Parser EXCEL_FILE_EXTENSIONS = ('xlsb', 'xls', 'xlsm', 'xla', 'xlt', 'xlam',) def parse(workbook_path): vba_path = workbook_path + '.vba' vba_parser = VBA_Parser(workbook_path) vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros() else [] for _, _, _, content in vba_modules: decoded_content = content.decode('latin-1') lines = [] if '\r\n' in decoded_content: lines = decoded_content.split('\r\n') else: lines = decoded_content.split('\n') if lines: name = lines[0].replace('Attribute VB_Name = ', '').strip('"') content = [line for line in lines[1:] if not ( line.startswith('Attribute') and 'VB_' in line)] if content and content[-1] == '': content.pop(len(content)-1) lines_of_code = len(content) non_empty_lines_of_code = len([c for c in content if c]) if non_empty_lines_of_code > 0: if not os.path.exists(os.path.join(vba_path)): os.makedirs(vba_path) with open(os.path.join(vba_path, name + '.bas'), 'w') as f: f.write('\n'.join(content)) if __name__ == '__main__': for root, dirs, files in os.walk('.'): for f in dirs: if f.endswith('.vba'): shutil.rmtree(os.path.join(root, f)) for f in files: if f.endswith(EXCEL_FILE_EXTENSIONS): parse(os.path.join(root, f)) 

有关更多详细信息,请参阅https://www.xltrail.com/blog/auto-export-vba-commit-hook