要找出 VBA 可用的内存量,请复制/粘贴下面的代码并调用availableMemoryInMB()
Function allocateMB(intNumMB As Integer) As Boolean
On Error Resume Next
Dim a As Variant
ReDim a(intNumMB, 256, 256) As Variant 'intNumMB x 256 x 256 x 16 bytes = intNumMB MB
allocateMB = (Err.Number = 0)
Err.Clear
Erase a
End Function
Function availableMemoryInMB() As Integer
Dim intLow As Integer, intHigh As Integer, intTest As Integer
intTest = 1: intHigh = 0
Do
If allocateMB(intTest) Then
intLow = intTest
If intHigh = 0 Then
intTest = intTest * 2
Else
intTest = (intLow + intHigh) / 2
End If
Else
intHigh = intTest
intTest = (intLow + intHigh) / 2
End If
Loop Until intHigh - intLow <= 1 And intHigh > 0
availableMemoryInMB = intLow
End Function
代码的执行需要 2-20 秒。在 64 位 Excel 版本中,几 GB 的内存可供 VBA 使用,而在 32 位版本的 Excel 中,大约有半 GB 可用。