我正在开发一个 VBA 项目,它将向另一个 Excel 工作簿插入一个模块。对于未受保护的工作簿,这种情况正在发生,但对于受保护的工作簿,我无法做到这一点。我也有密码。我如何使用 VBA 代码或 Python 代码来做到这一点?
Sub ImportVbaModuleToFiles()
Dim filePath As Variant
Dim wb As Workbook
Dim vbComp As Object
Dim modulePath As String
Dim moduleName As String
' Path to the VBA module file
modulePath = "C:\Users\user105\Documents\trial_imp.bas"
moduleName = "trial_imp" ' Change to the actual name of your module
' List of Excel files to import the module into
Dim excelFiles As Variant
excelFiles = Array("C:\Users\user105\Desktop\SAS\link_excel_warning\A.xlsm", "C:\Users\user105\Desktop\SAS\link_excel_warning\B.xlsm")
For Each filePath In excelFiles
Set wb = Workbooks.Open(filePath)
If Not ModuleExists(wb, moduleName) Then
Set vbComp = wb.VBProject.VBComponents.Import(modulePath)
MsgBox "Module imported to " & filePath
Else
MsgBox "Module already exists in " & filePath
End If
wb.Close SaveChanges:=True
Next filePath
End Sub
Function ModuleExists(wb As Workbook, moduleName As String) As Boolean
Dim vbComp As Object
For Each vbComp In wb.VBProject.VBComponents
If vbComp.Name = moduleName Then
ModuleExists = True
Exit Function
End If
Next vbComp
ModuleExists = False
End Function