Excel VBA中关于应用程序事件的运行问题
本人初学VBA程序事件,是个菜鸟,有点犯晕,想请教一下加载宏文件(内有应用程序事件代码)后,对Workbook进行操作时,所遇到的疑问,问题描述如下:1.分别加载事先保存...
本人初学VBA程序事件,是个菜鸟,有点犯晕,想请教一下加载宏文件(内有应用程序事件代码)后,对Workbook进行操作时,所遇到的疑问,问题描述如下:1. 分别加载事先保存的两个加载宏文件 “欢迎新建工作表.xlam”和“无权新建工作 表.xlam”2. 两个加载宏文件的代码分别如下:'欢迎新建工作表.xlam'Public WithEvents app1 As Excel.ApplicationPrivate Sub app1_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)MsgBox "欢迎新建工作表"End SubPrivate Sub Workbook_Open()Set app1 = Excel.ApplicationEnd Sub'无权新建工作表.xlam'Public WithEvents app2 As Excel.ApplicationPrivate Sub app2_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)Application.DisplayAlerts = FalseMsgBox "无权新建工作表"Sh.DeleteApplication.DisplayAlerts = TrueEnd SubPrivate Sub Workbook_Open()Set app2 = Excel.ApplicationEnd Sub当在Workbook中用鼠标点击左下侧 新工作表 时,依次出现对话框“无权新建工作表”以及“欢迎新建工作表”(见动图1),我的疑问是:1.为什么先运行的不是“欢迎新建工作表.xlam”? 2. 为何“欢迎新建工作表.xlam”运行后,却没有新建工作表?
将上述代码重新排版整,再次提交:
'无权新建工作表.xlam
Public WithEvents app2 As Excel.Application
Private Sub app2_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
Application.DisplayAlerts = False
MsgBox "无权新建工作表"
Sh.Delete
Application.DisplayAlerts = True
End Sub
Private Sub Workbook_Open()
Set app2 = Excel.Application
End Sub
'欢迎新建工作表.xlam
Public WithEvents app1 As Excel.Application
Private Sub app1_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
MsgBox "欢迎新建工作表"
End Sub
Private Sub Workbook_Open()
Set app1 = Excel.Application
End Sub 展开
将上述代码重新排版整,再次提交:
'无权新建工作表.xlam
Public WithEvents app2 As Excel.Application
Private Sub app2_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
Application.DisplayAlerts = False
MsgBox "无权新建工作表"
Sh.Delete
Application.DisplayAlerts = True
End Sub
Private Sub Workbook_Open()
Set app2 = Excel.Application
End Sub
'欢迎新建工作表.xlam
Public WithEvents app1 As Excel.Application
Private Sub app1_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
MsgBox "欢迎新建工作表"
End Sub
Private Sub Workbook_Open()
Set app1 = Excel.Application
End Sub 展开
1个回答
展开全部
这是因为你没有给出判断,但在新增工作表时两个事件都触发了。导致新建后再次被删除
我加了一个小条件,你自己看一下,琢磨下是怎么回事
Public WithEvents app2 As Excel.Application
Public WithEvents app1 As Excel.Application
Private Sub Workbook_Open()
Set app2 = Excel.Application
Set app1 = Excel.Application
End Sub
Private Sub app1_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
MsgBox "欢迎新建工作表"
End Sub
Private Sub app2_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
If Application.DisplayAlerts = False Then
MsgBox "无权新建工作表"
Sh.Delete
Application.DisplayAlerts = True
End If
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |