我有一个简单的小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 :(得分:4)
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
修改强>
我刚试过,下面似乎有效。在DoEvents
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