2014-01-15 70 views
4

我有一個簡單的小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 
+0

添加DoEvents是的,它是一個衆所周知的問題(我希望如此)。讓我發佈爲什麼發生這種情況:) –

+0

順便說一句,當我說「我希望如此」時,我的意思是我希望很多人都知道這種限制... –

回答

4

在Excel中的移位鍵用來打開工作簿打開該文件,但不運行宏,這會干擾運行宏的其餘部分。

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

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 
+0

工程!謝謝! –