如何确保热键仅为活动工作簿启动UserForm?

时间:2015-06-04 18:09:22

标签: excel vba excel-vba

在模板的workbook_open事件中,我注册了一个热键^m以启动用户窗体DataValidation

Private Sub workbook_open()

Application.OnKey "^m", "launchDataValidation"

End Sub

Sub launchDataValidation()

DataValidation.Show

End Sub

可能会有多个工作簿同时打开,这些工作簿是从此模板构建的。我想确保当用户按下热键时,启动的UserForm来自活动工作簿,以便该UserForm执行的任何操作只会影响该工作簿。

我尝试将launchDataValidation重写为:

Sub launchDataValidation()

On Error GoTo errHandler

ActiveWorkbook.DataValidation.Show
Exit Sub

errHandler:

End Sub

目的是打开活动工作簿的DataValidation表单,如果活动图书没有DataValidation表单,则不会发生任何事情。但相反,ActiveWorkbook.DataValidation.Show调用会转到错误处理程序,这表明这不是在活动工作簿中打开该表单的正确方法。

我也尝试过:

Sub launchDataValidation()

Dim bkName As String
Dim runString As String

bkName = ActiveWorkbook.Name
runString = "'" & bkName & "'!DataValidation.Show"

On Error GoTo errHandler

Application.Run runString

Exit Sub

errHandler:

End Sub

这也引发了一个错误。

1 个答案:

答案 0 :(得分:0)

想出来:

Private Sub workbook_open()

Application.OnKey "^m", "launchDataValidation_ActiveBook"

End Sub


Sub launchDataValidation()

DataValidation.Show

End Sub


Sub launchDataValidation_ActiveBook()

Dim bkName As String
Dim runString As String

bkName = ActiveWorkbook.Name
runString = "'" & bkName & "'!launchDataValidation"

On Error GoTo errHandler

Application.Run runString

Exit Sub

errHandler:

End Sub