新建From1(窗体),新建Command1-4(按钮CommandButton),代码:
Private Sub Command1_Click()
Dim arrA() As String
ReDim arrA(10)
Debug.Print VarPtr(arrA(0))
ReDim arrA(20)
Debug.Print VarPtr(arrA(0))
Debug.Print String$(10, "-")
End Sub
Private Sub Command2_Click()
Dim arrA() As String
ReDim arrA(20)
Debug.Print VarPtr(arrA(0))
ReDim arrA(10)
Debug.Print VarPtr(arrA(0))
Debug.Print String$(10, "-")
End Sub
Private Sub Command3_Click()
Dim arrA() As String
ReDim arrA(10)
Debug.Print VarPtr(arrA(0))
ReDim Preserve arrA(20)
Debug.Print VarPtr(arrA(0))
Debug.Print String$(10, "-")
End Sub
Private Sub Command4_Click()
Dim arrA() As String
ReDim arrA(20)
Debug.Print VarPtr(arrA(0))
ReDim Preserve arrA(10)
Debug.Print VarPtr(arrA(0))
Debug.Print String$(10, "-")
End Sub
Private Sub Command5_Click()
Dim arrA() As String
ReDim arrA(10)
Debug.Print VarPtr(arrA(0))
ReDim Preserve arrA(10)
Debug.Print VarPtr(arrA(0))
Debug.Print String$(10, "-")
End Sub
运行结果:
233366432
233630208
----------
233630208
233366488
----------
233366488
233630208
----------
233630208
233366432
----------
233366432
233366432
----------
证明了ReDim Preserve不管是扩大还是缩小数组都会分配新地址(被CPU复制了数据,使用了资源),但是不扩大和缩小,就不变。