VBA Excel:将代码插入到其他工作簿中不执行workbooks.open命令

时间:2013-08-21 10:00:36

标签: excel vba file-io insert

我将此工作簿中的代码注入到其他工作簿中,这些工作簿将执行一些子工作到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 ...

0 个答案:

没有答案