I actually ran into this exact problem myself and finally found a solution to my problem.
It is the Shift button in the keyboard shortcut you are using to call your code.
Apparently there a feature in Excel specifically designed to prevent code from running when a workbook is opened and the Shift key is pressed, but unfortunately this also impacts opening workbooks with the Workbook.Open
method via VBA. This was mentioned in KB Article 555263, applying to Excel 2000 & 2003, but I encountered the same problem in Excel 2010, so I imagine it is also impacting 2007 as well.
This occurs specifically when you try to open a workbook via code very early in the program. If the Workbook.Open
call is reached in code before you have had sufficient time to actually let go of the Shift button, Excel is interpreting that as an attempt to block code from running and aborts the process. And there are no error messages or anything that I have found. It just stops abruptly.
The workaround/fix is to force the code to wait for the Shift key to be released before issuing the Workbook.Open
command.
Per the article, just add this code to your macro and that should do it:
'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 Filename:="C:\MyPath\MyFile.xlsx"
End Sub
(NOTE: This code is for 32-bit versions of Excel. 64-bit versions will need to use the PtrSafe
attribute on the Declare
statement).
If you don't want to add the extra code, then your only other options are to not use Ctrl+Shift+Some Letter to launch a macro, or to put the Workbook.Open
command later in the macro (not right at the beginning) in order to give yourself time to release the Shift button after starting it.