Knowledge Base

External Procedure Declaration Can Cause Crash in MS Excel

Article ID: 152206

Article Last Modified on 10/10/2006


APPLIES TO


This article was previously published under Q152206

SUMMARY

A missing data type of the value returned by an external DLL function can cause Microsoft Excel to crash. If the prototype for the function is not VOID, the "Declare" statement should specify the correct return value.

MORE INFORMATION

For example, to get the Windows Directory, the GetWindowsDirectory function from the Windows API could be used from VBA. The prototype for GetWindows Directory is:
   UINT GetWindowsDirectory(
      LPTSTR lpBuffer,    // address of buffer for Windows directory
      UINT uSize  // size of directory buffer
      );
				
Following is the VBA code that will cause an Application Error during the calling of GetWindowsDirectory:
   Declare Function GetWindowsDirectory Lib "kernel32.dll" _
      Alias "GetWindowsDirectoryA" _
      (ByVal lpBuffer As String, ByVal uSize As Long)

   Sub ThisCrashes()
      Dim lpBuffer As String
      Dim uSize As Long
      uSize = 100
      lpBuffer = Space(uSize)
      GetWindowsDirectory lpBuffer, uSize
      MsgBox lpBuffer
   End Sub
				
If the following Declare statement is used, specifying the return type, the procedure works correctly:
   Declare Function GetWindowsDirectory Lib "kernel32.dll" _
      Alias "GetWindowsDirectoryA" _
    (ByVal lpBuffer As String, ByVal uSize As Long) As Long
				

Additional query words: 3.50 3.51 4.00 xlsdk xldk vba XL7

Keywords: kbdtacode KB152206