Skip to content

Windows API on 64 bit Office

Daniele Penza edited this page Dec 1, 2026 · 1 revision

πŸͺŸ Windows API on 64-bit Office

Evidence Office Declare

Most API tricks in older VBA books assume 32-bit pointers. On 64-bit Office they read or write the wrong memory, and Excel closes without an error message.

🟠 Every Declare call costs about 1.7 us

πŸ“ 1,000,000 calls:

Call Per call Ratio
VBA Private Function 41 ns 1.0x
GetCurrentProcessId (does almost nothing) 1,703 ns 42x
QueryPerformanceCounter with Currency 1,699 ns 42x
QueryPerformanceCounter with LongLong 1,672 ns 41x

βœ… An API call pays off only when it replaces a lot of VBA work. Keep API calls out of hot loops, call once and reuse the result.

🟠 CopyMemory: when it pays off

One call moves any number of bytes at memory speed; a VBA loop costs about 20 ns per Double. Break-even: about 100 elements per call.

Task VBA CopyMemory Verdict
Copy a whole numeric array (1,000,000 Double) b = a: 0.8 ms 0.8 ms βœ… use b = a, no API
Copy a slice (1,000,000 of 2,000,000) For loop: 20 ms 0.9 ms 24x; worth it only when repeated
Insert 500 values into a sorted array of 100,000 For loop shift: 516 ms 8.7 ms βœ… 59x: large overlapping moves, repeated
Swap two string pointers index swap: 17 ns 5.1 us ❌ 300x slower: never
#If VBA7 Then
    Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
        (ByRef Destination As Any, ByRef Source As Any, ByVal Length As LongPtr)
#Else
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
        (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)
#End If

' Insert x at position pos of a(1 .. cnt): shift the tail right by one.
' a() must already have room for one more element.
CopyMemory a(pos + 1), a(pos), (cnt - pos + 1) * LenB(a(1))   ' overlapping is safe
a(pos) = x

Important

Rules for CopyMemory on 64-bit Office:

  • Declare PtrSafe, with the length As LongPtr;
  • addresses in LongPtr variables, passed ByVal; array elements passed ByRef;
  • length = elements x LenB of one element;
  • numeric element types only: never String, Object or Variant elements;
  • a zero length is harmless (πŸ“ contrary to the classic advice).

βœ… Before reaching for CopyMemory to insert into a sorted array, ask whether collecting the values and sorting once avoids the inserts altogether.

🟠 Waiting for an external process

πŸ“ cmd /c exit 3, wait for it, read the exit code:

Method Per run Ratio
βœ… WScript.Shell.Run with wait 76 ms 1.0x
CreateProcessW + WaitForSingleObject 101 ms 1.33x
Sleep 100 + DoEvents polling 149 ms 2.0x
' βœ… simplest and fastest: no API
Public Function RunAndWait(ByVal CommandLine As String) As Long
    Dim sh As Object
    Set sh = CreateObject("WScript.Shell")
    RunAndWait = sh.Run(CommandLine, 0, True)   ' 0 = hidden, True = wait; returns the exit code
End Function

Warning

Do not wait on a process started with Shell: it returns a process ID only, and a short process can end before OpenProcess runs. Where Windows Script Host is disabled by policy, start the process with CreateProcessW, which returns the handle directly, and close both the process and the thread handle. A complete 32/64-bit version is in M_BookBench6.bas.

⚠️ 64-bit rules

Rule Why
Every Declare needs PtrSafe Required by VBA7
Handles, pointers and addresses (hProcess, hModule, VarPtr results) are LongPtr 8 bytes on 64-bit; a Long truncates them
Counts, flags and sizes stay Long They are 32-bit in the API
Close what you open (CloseHandle, FreeLibrary) Each leaked handle stays until Excel closes
Read errors with Err.LastDllError, never GetLastError VBA makes its own API calls in between (πŸ“ 3 = path not found)
Use the length an API returns instead of searching for vbNullChar πŸ“ GetSystemDirectoryW returned 19 = Len of the result
Prefer the W functions with StrPtr They keep Unicode paths intact
Dim buf As String, n As Long, sysDir As String
buf = String$(260, vbNullChar)
n = GetSystemDirectoryW(StrPtr(buf), Len(buf))
If n > 0 And n < Len(buf) Then sysDir = Left$(buf, n)

❌ Classic tricks to drop

Trick Why
Swapping strings by copying 4-byte descriptors Corrupts memory on 64-bit; even written correctly it is 300x slower than swapping indices
VarPtr(arr) + 8 to read array dimensions 32-bit offsets; use LBound / UBound with error handling
HiWord / LoWord through CopyMemory Plain arithmetic does it: v And &HFFFF&
SetTimer with an AddressOf callback An error in the callback crashes Excel; use Application.OnTime
Subclassing, undocumented ordinals (SHShutDownDialog), Windows 9x calls Crash risk or no use in Excel work

⚑ VBA Performance

Topics

Reference

Clone this wiki locally