为了防止在奇怪的环境中意外覆盖文件,我在excel文件中劫持了保存。
Workbook_BeforeSave和Workbook_BeforeClose事件完全靠自己工作。不幸的是,代码当前的结构方式,我需要在BeforeClose事件中调用BeforeSave事件。
在最基本的形式中,以下代码不会按照我的意愿执行。在以下示例中,如果在BeforeClose事件中调用save,则wksHiddenWorksheet.Visible = True将不会使wksHiddenWorksheet可见。
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Save
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
wksHiddenWorksheet.Visible = True
End Sub
这有什么办法吗?以我正在尝试的方式从另一个事件中调用事件是不是很糟糕的做法(甚至从根本上是不正确的)?
更新
我在工作簿中使用过Application.EnableEvents,但我确保在错误处理中它总是恢复为True。
我已经打开了一个全新的工作簿并输入了以下代码
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Debug.Print Application.EnableEvents 'Prints TRUE
ThisWorkbook.Save
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'The workbook consists of two sheets. Sheet1 and Sheet2
Sheet1.Visible = xlSheetHidden
Debug.Print Sheet1.Visible 'Prints -1 (xlSheetVisible)
End Sub
Visible工作表不会被隐藏,但如果我逐行浏览代码,则会触发该行。如果我在同一空间中输入MsgBox等代码,MsgBox将正常打开。
更新2:
要回答每个人的问题并准确显示所发生的情况,请参阅以下代码:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'The workbook consists of two sheets. Sheet1 and Sheet2
Debug.Print Application.EnableEvents 'Prints TRUE
Debug.Print Sheet1.Visible 'Prints -1 (xlSheetVisible)
Sheet1.Visible = xlSheetHidden
Sheet1.Visible = False 'Same thing
Debug.Print Sheet1.Visible 'Prints 0 (xlSheetHidden)
Sheet1.Visible = xlSheetVisible
Sheet1.Visible = True 'Same thing
Debug.Print Sheet1.Visible 'Prints -1 (xlSheetVisible)
ThisWorkbook.Save
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Debug.Print Sheet1.Visible 'Prints -1 (xlSheetVisible)
Sheet1.Visible = xlSheetHidden
Sheet1.Visible = False 'Same thing
'Sheet1 should now be hidden, but it's not
Debug.Print Sheet1.Visible 'Prints -1 (xlSheetVisible)
End Sub
隐藏和取消隐藏工作表在第一个事件中完美运行,但是一旦触发第二个事件,工作表可见性就不会改变。
更新3:
另一点。如果我直接(通过保存)输入Workbook_BeforeSave()事件,而不是从Workbook_BeforeClose()事件中输入它,那么一切都按预期工作。
稍后更新:
虽然我将这个问题标记为刚刚解决,但我遇到了一篇有助于解释行为的文章。可以在以下位置找到解释: http://www.cpearson.com/excel/events.aspx
答案 0 :(得分:2)
已修改
以下代码适用于我
{
xtype: 'filefield',
cls: 'reset',
width: 357,
fieldLabel: 'Upload Logo',
name: 'file',
allowBlank: false,
emptyText: 'Browse Location...',
size: 40,
validateBlank: true,
vtype: 'fileUpload',
buttonText: 'Browse',
listeners: {
change: {
fn: me.onFilefieldChange,
scope: me
}
}
},
{
xtype: 'button',
handler: function(){
Message.waitForLoading();
var form = this.up('logoandcoloring').getForm();
if (form.isValid()){
form.submit({
// and later processing the request
很难说出为什么......
答案 1 :(得分:1)
在此示例中,从HideSheet
和BeforeSave
事件处理程序调用过程BeforeClose
。因此两个处理程序都隐藏了工作表。 HTH
Private Sub Workbook_BeforeClose(Cancel As Boolean)
HideSheet Sheet1
ThisWorkbook.Save
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
HideSheet Sheet1
End Sub
Private Sub HideSheet(wks As Worksheet)
wks.Visible = xlSheetHidden
End Sub