关闭跳过open命令之前的vba工作簿

时间:2016-03-14 15:49:57

标签: excel vba excel-vba

我有三本工作簿,一本父书,一本图书馆和一本日志。

父书打开一个库,然后关闭库。巧合的是,图书馆在开放和关闭事件之前的工作簿中都有一个条款,可以在打开或关闭时写入日志。

我的问题是,当从父书以编程方式打开库时,将跳过在关闭之前打开日志的代码。我没有错误,只是简单地评估该行并且没有产生任何结果。

CODE:

从我的父书中我运行这一行:

...
Workbooks(parts_library_name).Close savechanges:=True
...

在图书馆书中运行此代码:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set libwkb = ThisWorkbook
'last call to backup usage sheet
backup_exit_size
'exit
End Sub

Sub backup_exit_size()
Dim bypass_close_usage_library As Boolean

Application.DisplayAlerts = False
file_size_at_close = FileLen(ThisWorkbook.Path & "\" & ThisWorkbook.Name)
For Each Workbook In Workbooks
    If Workbook.Name = "usage_library.xlsx" Then bypass_close_usage_library = True
Next
Application.ScreenUpdating = False
If bypass_close_usage_library = False Then
    Workbooks.Open "somepath\usage_library.xlsx"
End If
Workbooks("usage_library.xlsx").Worksheets("usage").Cells(next_row_usage_library, 3) = file_size_at_close
Workbooks("usage_library.xlsx").Close savechanges:=True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

问题是当它到达这一行时:

    Workbooks.Open "somepath\usage_library.xlsx"

编译器只是跳过命令。

但是,如果我进入源自另一本书的beforeClose事件,情况就是这样。如果我从自己关闭本书,宏运行正常并打开日志书。

我已尝试过父书中的with语句,例如

With library.xlsx
 .RunAutoMacros xlAutoClose 
 .Close 
End With

但结果相同,它会评估该行,然后跳过它。

思想?

3 个答案:

答案 0 :(得分:1)

我看到了同样的行为。我甚至尝试使用WithEvents

作为一种变通方法,您可以在新的Excel实例中打开新工作簿:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Dim xlapp As New Excel.Application
    Dim wb As Workbook
    Set wb = xlapp.Workbooks.Open("\\...\test.xlsb")
    xlapp.Visible = True 'This line just proves that it works and can be removed'
    'do stuff
    xlapp.Quit
    Set wb = Nothing
    Set xlapp = Nothing

End Sub

答案 1 :(得分:0)

这是我现在的解决方案:

...
Application.Run (parts_library_name & "!backup_exit_size")
Workbooks(parts_library_name).Close savechanges:=True
...

这可行,但可能不太理想。

答案 2 :(得分:0)

我已经确定了application.screenupdating = false所固有的问题。如果在工作簿打开命令之前将其关闭,它可以正常工作。