'Why is my Excel declaration crashing my file?

I have an Excel file that used to run fine in Excel 365 that now crashes. I've traced it down to a single line of code in my declarations section in my VBA code:

Private Declare Function apiShowWindow Lib "user32" Alias "ShowWindow" _
    (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long

Here's the question: just pasting this line of code into a brand-new Excel file causes a crash--when I try to save the file I get sharing violations, access violations, etc., etc. Even trying something like this:

#If VBA7 Then

Private Declare PtrSafe Function apiShowWindow Lib "user32" Alias "ShowWindow" _
    (ByVal hWnd As LongPtr, ByVal nCmdShow As Long) As Long

#Else

Private Declare Function apiShowWindow Lib "user32" Alias "ShowWindow" _
    (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long

#End If

doesn't solve the problem. Can someone help? Again--just putting the single line of code in a new file causes the crash when saving, whether or not I've set Trust Center to enable or disable all macros.



Solution 1:[1]

Windows API

  • You cannot rename an API function, its name is fixed. It is searched for in a library, in this case in user32.dll.
  • The following is working correctly on my machine Win 10 64bit Office 2019 64bit.
Option Explicit

#If VBA7 Then
    Private Declare PtrSafe Function ShowWindow _
        Lib "user32.dll" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
#Else
    Private Declare Function ShowWindow _
        Lib "user32.dll" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
#End If
  • You could do something like this...
Sub apiShowWindow(ByVal hwnd As Long, ByVal nCmdShow As Long)
    ShowWindow hwnd, nCmdShow
End Sub

... and use it e.g. like this...

Sub test()
    apiShowWindow Windows(1).hwnd, 0
End Sub

... though.

Or as a function:

Function api2ShowWindow(ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
    api2ShowWindow = ShowWindow(hwnd, nCmdShow)
End Function

Sub test2()
    Debug.Print api2ShowWindow(Windows(1).hwnd, 1)
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1