I'm trying to copy a large number of lines (20k to 65k) into new workbooks, and for some reason, assigning the value of the range I'm copying uses more memory than using the copy/paste buffer, which doesn't make any sense to me, unless I'm somehow doing this wrong.
This is the original code:
Public Const FIRSTSHEETTAB As String = "Sheet1"
' <snip>
Dim last_row As Long
Dim num_files As Long
Dim ps_rng As Range
' <snip>
Dim i As Long
Dim new_book As Workbook
Dim start_row As Long
Dim end_row
start_row = 2
For i = 1 To num_files
Set new_book = Workbooks.Add
end_row = start_row + max_lines - 1
If end_row > last_row Then
end_row = last_row
End If
With new_book
.Windows(1).Caption = "PS Upload " & i
With .Worksheets(FIRSTSHEETTAB)
.Range("1:1").Value2 = ps_rng.Range("1:1").Value2
.Range("2:" & max_lines).Value2 = ps_rng.Range(CStr(start_row) & ":" & CStr(end_row)).Value2
End With
End With
start_row = end_row + 1
Next i
And what I had to do to get this working was change .Range("2:" & max_lines).Value2 = ps_rng.Range(CStr(start_row) & ":" & CStr(end_row)).Value2 to the following:
ps_rng.Range(CStr(start_row) & ":" & CStr(end_row)).Copy
.Range("2:" & max_lines).PasteSpecial
And I don't understand why this works where as the former code runs out of memory. I'd much rather not have to overwrite whatever is in the copy/paste buffer if I can help it.
What's causing just the simple assignment to run out of memory?
UsedRangeof the sheet you're copying from: that way you're not copying 16k columns of what are likely mostly empty cells. As to why it works when you do a Copy - possibly Excel is smart enough to be able to automatically exclude unused cells.