MCPcopy Create free account
hub / github.com/dothinking/PyAddin / VBA

Class VBA

pyaddin/xlam/vba.py:5–104  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3
4
5class VBA:
6
7 def __init__(self, xlam_file:str, excel_app):
8 '''Process VBA modules for add-in file, e.g., add callback function based on ribbon menu.
9
10 Args:
11 xlam_file (str): Add-in filename.
12 excel_app (win32 COM object): The Excel application instance.
13 '''
14 self.xlam_file = xlam_file
15 if not os.path.exists(xlam_file):
16 raise AddInException(f'Not find add-in file: {self.xlam_file}.')
17
18 # current workbook
19 self.wb = excel_app.Workbooks.open(xlam_file)
20 self.wb.DoNotPromptForConvert = True
21 self.wb.CheckCompatibility = False
22
23
24 def save(self):
25 '''Save add-in.'''
26 self.wb.Save()
27
28
29 def import_module(self, module_file:str):
30 '''Import vba module from specified file (*.bas).
31
32 Args:
33 module_file (str): Module file with module name declared in the first line:
34 Attribute VB_Name = "xxxx"
35 '''
36 # check module name
37 with open(module_file, 'r') as f:
38 header = f.readline().strip()
39
40 if not header.startswith('Attribute VB_Name'):
41 raise AddInException('The first line of a valid module file should be: Attribute VB_Name = "xxxx"')
42
43 # delete module if existed already
44 module_name = header.split('"')[-2]
45 for comp in self.wb.VBProject.VBComponents:
46 if comp.Name == module_name:
47 self.wb.VBProject.VBComponents.Remove(comp)
48 break
49
50 # import module
51 self.wb.VBProject.VBComponents.Import(module_file)
52
53
54 def import_named_module(self, module_name:str, module_file:str):
55 '''Import vba code for specified module.
56
57 Args:
58 module_name (str): module name, e.g., sheet1, sheet2, thisWorkbook
59 module_file (str): Module file with module name declared in the first line:
60 Attribute VB_Name = "xxxx"
61 '''
62 code_module = self.wb.VBProject.VBComponents(module_name).codeModule

Callers 1

createMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected