Skip to content

Instantly share code, notes, and snippets.

@sancarn
Last active December 20, 2021 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sancarn/b453fb96041984e58c816280b9980ae2 to your computer and use it in GitHub Desktop.
Save sancarn/b453fb96041984e58c816280b9980ae2 to your computer and use it in GitHub Desktop.
VBA Deref/Dereference objects (Convert from ObjPtr to Object)

Deref

While making stdCOM for stdVBA, I ran into the need to dereference a pointer into a real VBA object. This was because I wanted to add an Object property to stdCOM objects, which enabled the retrieval of the full object data. I.E.

set cmApp = stdCOM.CreateFromPtr(ObjPtr(Application))
Debug.Print cmApp.Object.Name 'Print Application.Name

I had a load of issues with trying to find how to dereference an object, but finally stumbled upon some posts that suggesed using CopyMemory. I still found it difficult to find a x64 example, but eventually settled with the implementation in Deref.Bas.

This is now a part of stdCOM which may be useful to others, but if importing a whole class is overkill for your use case, feel free to use this GIST.

#If VBA7 Then
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Declare PtrSafe Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" (Destination As Any, ByVal Length As Long)
#Else
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" (Destination As Any, ByVal Length As Long)
#End If
Public Sub test()
Debug.Print Deref(ObjPtr(Application)).Name
End Sub
#If VBA7 Then
Private Function Deref(ByVal memAddress As LongPtr) As Object
#Else
Private Function Deref(ByVal memAddress As Long) As Object
#End If
Dim result As Object
CopyMemory result, ByVal varPtr(memAddress), LenB(memAddress)
Set Deref = result 'Set and add ref
ZeroMemory result, LenB(memAddress)
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment