Macro in Excel Stops After A Workbook.Open Command

Author:

Jan Karel Pieterse MVP

COMMUNITY SOLUTIONS CONTENT DISCLAIMER

MICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES.

SYMPTOMS

You are running code that is meant to open one or more files using the Workbooks.Open command.
As soon as you hold down the shift key when this command is being processed, macro execution stops and your program is terminated entirely.
This will even happen if you are e.g. editing an email message in Outlook whilst Excel VBA is processing the code in the background.

CAUSE

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.
 
Microsoft has confirmed this is a bug.

RESOLUTION

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
   
गुण

आलेख ID: 555263 - पिछली समीक्षा: 14/02/2017 - संशोधन: 1

Microsoft Office Excel 2003, Microsoft Excel 2000 Service Pack 1, Microsoft Excel 2000 Service Pack 3, Microsoft Excel 2000 Standard Edition, Microsoft Excel 2002 Service Pack 2, Microsoft Excel 2002 Standard Edition

प्रतिक्रिया