1

我将此工作簿中的代码注入到其他工作簿中,这些工作簿将在 Workbook_BeforeSave 中执行一些子操作。我必须这样做才能将工作表的内容保存到集中式工作簿中。我有 1 个中央工作簿和 100 颗卫星。

插入的命令之一是:

set workbooktostore = workbooks.open(storefile)

当我在注射结束时保存工作簿时,这个命令根本没有执行。当用户从卫星文件中单击保存时,我没有这个问题。

这里有一个例子:

Public sub Main
    dim workbooktoinject as workbook
    set workbooktoinject = workbooks.add

    INSERTVBCODE(workbooktoinject)
    workbooktoinject.saveas "C:\satellite1.xlsm", xlOpenXMLWorkbookMacroEnabled
End Sub

Private Sub INSERTVBCODE(WorkbookToUpdate As Workbook)
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim CodeMod As VBIDE.CodeModule
    Dim LineNum As Long
    Set VBProj = WorkbookToUpdate.VBProject
    Set VBComp = VBProj.VBComponents("ThisWorkbook")
    Set CodeMod = VBComp.CodeModule

    CodeMod.InsertLines LineNum, "Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    dim workbooktostore as workbook"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    dim storefile as string"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    storefile=""C:\storefile.xlsx"""
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    msgbox ""Test display"""
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    set workbooktostore = workbooks.open(storefile)"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    msgbox workbooktostore.readonly"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "    workbooktostore.close"
    LineNum = LineNum + 1
    CodeMod.InsertLines LineNum, "end sub"
end sub

当您执行 Main 时,这会导致 ONE msgbox 显示“Test display”。但是当您单击保存到 staellite1.xlsm 时,您应该会看到第二个 msgbox 显示“false”。执行 SaveAs 时,我期待相同的 msgbox...

4

0 回答 0