我使用VB6,我需要做一个ReDim保存到一个多维数组:
Dim n,m As Integer n = 1 m = 0 Dim arrCity() As String ReDim arrCity(n,m) n = n + 1 m = m + 1 ReDim Preserve arrCity(n,m)
每当我这样做,我写了它,我得到以下错误:
runtime error 9: subscript out of range
因为我只能改变最后的数组维度,在我的任务中,我必须改变整个数组(在我的例子中为2个维度)!
正确指出,ReDim只能保留阵列的最后一个维度(MSDN上的
ReDim Statement):
If you use the Preserve keyword,you can resize only the last array
dimension and you can’t change the number of dimensions at all. For
example,if your array has only one dimension,you can resize that
dimension because it is the last and only dimension. However,if your
array has two or more dimensions,you can change the size of only the
last dimension and still preserve the contents of the array
因此,决定的第一个问题是二维数组是否是该作业的最佳数据结构.可能,一维数组是更适合您需要做的ReDim Preserve?
另一种方法是按照Pieter Geerkens’s suggestion使用锯齿形阵列.在VB6中没有直接支持锯齿状数组.在VB6中编写“数组数组”的一种方法是声明一个Variant数组,并使每个元素成为所需类型的数组(在你的情况下为String).演示代码如下.
另一个选择是自己实现Preserve部分.为此,您需要创建要保留的数据副本,然后使用它填充重新定义的数组.
Option Explicit Public Sub TestMatrixResize() Const MAX_D1 As Long = 2 Const MAX_D2 As Long = 3 Dim arr() As Variant InitMatrix arr,MAX_D1,MAX_D2 PrintMatrix "Original array:",arr ResizeMatrix arr,MAX_D1 + 1,MAX_D2 + 1 PrintMatrix "Resized array:",arr End Sub Private Sub InitMatrix(a() As Variant,n As Long,m As Long) Dim i As Long,j As Long Dim StringArray() As String ReDim a(n) For i = 0 To n ReDim StringArray(m) For j = 0 To m StringArray(j) = i * (m + 1) + j Next j a(i) = StringArray Next i End Sub Private Sub PrintMatrix(heading As String,a() As Variant) Dim i As Long,j As Long Dim s As String Debug.Print heading For i = 0 To UBound(a) s = "" For j = 0 To UBound(a(i)) s = s & a(i)(j) & "; " Next j Debug.Print s Next i End Sub Private Sub ResizeMatrix(a() As Variant,m As Long) Dim i As Long Dim StringArray() As String ReDim Preserve a(n) For i = 0 To n - 1 StringArray = a(i) ReDim Preserve StringArray(m) a(i) = StringArray Next i ReDim StringArray(m) a(n) = StringArray End Sub