Input Box doesn't appear when macro is run from shortcut key

廉价感情. 提交于 2019-12-05 18:16:07

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!