从快捷键运行宏时不出现输入框
Posted
技术标签:
【中文标题】从快捷键运行宏时不出现输入框【英文标题】:Input Box doesn't appear when macro is run from shortcut key 【发布时间】:2014-02-04 01:26:14 【问题描述】:我有一个简单的 Excel 小宏,它可以打开模板、询问文件名并保存文件。它从 Microsoft VBA 窗口运行没有问题,但是当从 Excel 使用快捷键时,它会打开文件,但不显示输入框。
Sub NewCommentSheet()
'
' NewCommentSheet Macro
' Opens the Comments and Recheck template. A dialog box asks for the data module name,
' which is then used for the filename of the new comment sheet.
'
' Keyboard Shortcut: Ctrl+Shift+N
'
'Opens the file
Workbooks.Open Filename:= _
"C:\Users\Kelly.Keck\Documents\Projects\SBIR\QA Notes\Comments and Recheck Template.xlsx"
'Defines variables. moduleName comes from the input box. newFileName uses moduleName _
to create a filename: "Comments for [moduleName].xslx"
Dim moduleName As String
Dim newFileName As String
'Asks the user for the data module name--default is set as the common portion of _
the filename.
moduleName = Application.InputBox(Prompt:="Enter the name of the data module.", _
Title:="Data Module Title", Default:="DMTitle-")
'Checks to see if input was canceled. If canceled, ends the macro to avoid saving with an incorrect filename.
If moduleName = "False" Then End
'Saves file with the new name.
newFileName = "Comments for " & moduleName & ".xslx"
ActiveWorkbook.SaveAs Filename:=newFileName
End Sub
【问题讨论】:
是的,这是一个众所周知的问题(我希望如此)。让我发布为什么会这样:) 顺便说一句,当我说“我希望如此”时,我的意思是我希望很多人都知道这个限制...... 【参考方案1】:Excel 中的 Shift 键用于打开工作簿以在不运行宏的情况下打开文件,这会干扰宏的其余部分的运行。
来自MSDN文章
Excel 设计为在按住 shift 键的同时从用户界面打开工作簿时不运行 Auto_Open 和 Workbook_Open 代码。不幸的是,这种(期望的)行为也适用于通过 VBA 代码打开工作簿时。
上述链接的解决方案(以防链接失效)
此问题的解决方法(仅适用于 Windows ® 平台)是检测是否按下了 shift 键并等待它释放后再发出 Workbooks.Open 命令:
'Declare API
Declare Function GetKeyState Lib "User32" (ByVal vKey As Integer) As Integer
Const SHIFT_KEY = 16
Function ShiftPressed() As Boolean
'Returns True if shift key is pressed
ShiftPressed = GetKeyState(SHIFT_KEY) < 0
End Function
Sub Demo()
Do While ShiftPressed()
DoEvents
Loop
Workbooks.Open = "C:\My Documents\ShiftKeyDemo.xls"
End Sub
编辑
我刚刚进行了实验,以下似乎可行。在Workbooks.Open
前添加DoEvents
Sub NewCommentSheet()
Dim moduleName As String
Dim newFileName As String
DoEvents
Workbooks.Open Filename:= _
"C:\book1.xlsx"
moduleName = Application.InputBox(Prompt:="Enter the name of the data module.", _
Title:="Data Module Title", Default:="DMTitle-")
If moduleName = "False" Then End
'Saves file with the new name.
newFileName = "Comments for " & moduleName & ".xslx"
ActiveWorkbook.SaveAs Filename:=newFileName
End Sub
【讨论】:
以上是关于从快捷键运行宏时不出现输入框的主要内容,如果未能解决你的问题,请参考以下文章