从快捷键运行宏时不出现输入框

Kel*_*eck 4 excel vba inputbox

我有一个简单的小 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
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 5

Excel 中的键Shift用于打开工作簿以打开文件而不运行宏,这会干扰宏的其余部分的运行。

\n\n

来自MSDN文章

\n\n
\n

Excel 设计为在按住 Shift 键的同时从用户界面打开工作簿时不运行 Auto_Open 和 Workbook_Open 代码。不幸的是,当通过 VBA 代码打开工作簿时,这种(所需的)行为也适用。

\n
\n\n

来自上述链接的解决方案(如果链接失效)

\n\n

此问题的解决方法(仅适用于 Windows \xc2\xae 平台)是检测是否按下了 Shift 键并等待其释放,然后再发出 Workbooks.Open 命令:

\n\n
\'Declare API\nDeclare Function GetKeyState Lib "User32" (ByVal vKey As Integer) As Integer\nConst SHIFT_KEY = 16\n\nFunction ShiftPressed() As Boolean\n    \'Returns True if shift key is pressed\n    ShiftPressed = GetKeyState(SHIFT_KEY) < 0\nEnd Function\n\nSub Demo()\n    Do While ShiftPressed()\n        DoEvents\n    Loop\n    Workbooks.Open = "C:\\My Documents\\ShiftKeyDemo.xls"\nEnd Sub\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑

\n\n

我刚刚尝试过,下面的内容似乎有效。DoEvents在之前添加Workbooks.Open

\n\n
Sub NewCommentSheet()\n    Dim moduleName As String\n    Dim newFileName As String\n\n    DoEvents\n\n    Workbooks.Open Filename:= _\n        "C:\\book1.xlsx"\n\n    moduleName = Application.InputBox(Prompt:="Enter the name of the data module.", _\n    Title:="Data Module Title", Default:="DMTitle-")\n\n    If moduleName = "False" Then End\n\n    \'Saves file with the new name.\n\n    newFileName = "Comments for " & moduleName & ".xslx"\n    ActiveWorkbook.SaveAs Filename:=newFileName\nEnd Sub\n
Run Code Online (Sandbox Code Playgroud)\n