Your problem is that you are shuffling millions of megabytes of memory. At the halfway point your code is copying 5.7 MBytes from one memory location to another each time through the inner loop. A total off 5,700 Gigabytes over the entire program.
The rules are join small strings together then join the smaller strings at the end of the concatenation. To make the smaller strings no larger than say 4000 bytes then join those files at the end.
Modern languages have a string builder object, VBA has one too it's just not called that.
In VBA there is the Mid
function and the Mid
statement. They do opposite things. So you create your final sting first. Then using the Mid
statement pop your substrings into the first string. This avoids all the 100s of megabytes of shuffling. Use Rtrim
to lop off any excess spaces at the end. If you Dim the Output to 6 million spaces then it will fit in your example, and use about 12 MBytes compared to thousands of Gigabytes.
Here is a small example.
Private Sub Form_Load()
OutPut = Space(1500)
For x = 1 To 500
Offset = Offset + Len(CStr(x))
Mid(OutPut, Offset) = CStr(x)
Next
MsgBox OutPut
End Sub
See Pointers needed for speeding up nested loop macro in VBA