Code:
Option Explicit
Private Type CellStruct
sText As String
Width As Long
Height As Long
Font As StdFont
ForeColor As OLE_COLOR
'...other boolean type and Long type member
End Type
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, _
lpvSource As Any, _
ByVal cbCopy As Long)
Private Type CellLine
Cols() As CellStruct
End Type
Private m_CellRows() As CellLine
Private Sub Form_Load()
Dim i As Long, j As Long, copysize As Long
Dim myfont(3) As New StdFont
ReDim m_CellRows(3)
For i = 0 To 3
myfont(i).Name = "Tahoma"
myfont(i).Size = 10 + i
ReDim m_CellRows(i).Cols(1)
For j = 0 To 1
m_CellRows(i).Cols(j).sText = "Test String"
m_CellRows(i).Cols(j).Height = j
Set m_CellRows(i).Cols(j).Font = myfont(i)
Next
Next
For i = 0 To 3
ReDim Preserve m_CellRows(i).Cols(1)
For j = 0 To 1
Debug.Print i & ":" & j, m_CellRows(i).Cols(j).sText, m_CellRows(i).Cols(j).Font.Size
Next
Next
For i = 3 To 2 Step -1
m_CellRows(i) = m_CellRows(i - 1) '2-->3 1-->2
Next
'copysize = LenB(m_CellRows(0))
'copysize = copysize * 2
'CopyMemory ByVal VarPtr(m_CellRows(2)), ByVal VarPtr(m_CellRows(1)), copysize
For i = 0 To 3
ReDim Preserve m_CellRows(i).Cols(1)
For j = 0 To 1
Debug.Print i & ":" & j, m_CellRows(i).Cols(j).sText, m_CellRows(i).Cols(j).Font.Size
Next
Next
End Sub
For i = 3 To 2 Step -1
m_CellRows(i) = m_CellRows(i - 1) '2-->3 1-->2
Next
Considering a huge m_CellRows with 1000 elements and 100 Cols (m_CellRows(999).Cols(99)), what is the fast way to shift position when inserting at index 2?
As above, we can use:
For i = 999 To 2 Step -1
m_CellRows(i) = m_CellRows(i - 1) '998-->999 997-->998,996-->997... (999 goes away)
Next
I am trying to use CopyMemory to increase performance, But I am not sure what is reliability and memory leak, looks like failed at some time:
copysize = LenB(m_CellRows(0)) '= 4
copysize = copysize * (999-2) 'shifting ONE position for #2 till #999,old #999 goes away
CopyMemory ByVal VarPtr(m_CellRows(3)), ByVal VarPtr(m_CellRows(2)), copysize
I may confuse you too much, For my case,what is the proper way to use CopyMemory to shift one position for m_CellRows from position 2 till last elements? Please take note UDT array m_CellRows has Font Object and sText string elements.