I have a simple little Excel macro that opens a template, asks for a filename, and saves the file. It runs from the Microsoft VBA window without issues, but when the shortcut key is used from Excel, it opens the file, but doesn't show the input box.
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
The Shift key in Excel is used to open a workbook to open the file without running macros and this interferes with running the rest of the macro.
From MSDN article
Excel is designed not to run Auto_Open and Workbook_Open code when a workbook is opened from the User interface whilst holding down the shift key. Unfortunately, this (desired) behaviour also applies when opening workbooks through VBA code.
Resolution from the above link (In case the link dies)
The workaround for this problem (only applicable on Windows ® platforms) is to detect whether the shift key is pressed and wait for it to be released before issuing the Workbooks.Open command:
'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
EDIT
I just experimented and the below seems to work. Adding DoEvents
before the Workbooks.Open
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
来源:https://stackoverflow.com/questions/21139758/input-box-doesnt-appear-when-macro-is-run-from-shortcut-key