Repository navigation
Windows API on 64 bit Office
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.
π 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.
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) = xImportant
Rules for CopyMemory on 64-bit Office:
-
Declare PtrSafe, with the lengthAs LongPtr; - addresses in
LongPtrvariables, passedByVal; array elements passedByRef; - length = elements x
LenBof one element; -
numeric element types only: never
String,ObjectorVariantelements; - 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.
π 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 FunctionWarning
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.
| 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)| 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 |
π Figures: Excel 365 (16.0 build 20723) 64-bit, Windows desktop, median of 5 runs Β· Raw data in docs/benchmarks/
- π Home
- π Measurement Method
Topics
- π Working with Excel
- π¦ Passing Data
- π€ Strings
- π’ Numbers and Dates
- π Searching, Sorting and Collections
- π§© Calls, Classes and Binding
- π Files and CSV
- πͺ Windows API on 64-bit Office
Reference
β οΈ Correctness Traps- π§° Skill Rules