【发布时间】:2013-11-08 09:14:16
【问题描述】:
我在 VBA 中调整二维数组的大小时遇到了严重问题。我已经阅读了很多关于这个(流行)问题的资料,但我仍然无法弄清楚我的代码有什么问题。
所以,我在电子表格中有一些数据。在第二行中,我有一些元素的描述,而在第一行中,我有这些元素的类别。我想要做的是创建一个数组,该数组在第一行中具有(不同的)类别,在第二行中具有与特定类别相关的描述索引。 代码正常工作,直到 如果 j = UBound(distinctList, 2) 那么 然后 ReDim 进来了,我得到一个“下标超出范围错误”。 如果电子表格中的条目不等于新数组中的任何条目,则该 If 用于添加新类别。
Function distinctValues(arr)
Dim distinctList() As String
Dim j As Integer
k = 0
'ReDim distinctList(0 To 0, 0 To 1)
'Dodaj pierwszy wpis
For i = LBound(arr) To UBound(arr)
If arr(i) <> "" Then
ReDim distinctList(0 To 1, 0 To j)
distinctList(0, 0) = arr(i)
distinctList(1, 0) = i + 1
'k = k + 1
Exit For
End If
Next i
'Dodaj kolejne wpisy
For i = LBound(arr) + 1 To UBound(arr)
If arr(i) <> "" Then
For j = LBound(distinctList, 2) To UBound(distinctList, 2)
If arr(i) = distinctList(0, j) Then
distinctList(1, j) = distinctList(1, j) & ", " & i + 1
'k = k + 1
Exit For
End If
If j = UBound(distinctList, 2) Then
ReDim Preserve distinctList(0 To 1, 1 To UBound(distinctList, 2) + 1)
distinctList(0, j) = arr(i)
distinctList(1, j) = distinctList(UBound(distinctList, 2), 1) & ", " & i + 1
Exit For
End If
Next j
End If
Next i
Debug.Print distinctList(0, 0) & " => " & distinctList(1, 0)
'distinctValues = distinctList
End Function
【问题讨论】:
-
以这种方式重新调整:
ReDim Preserve distinctList(1, UBound(distinctList, 2) + 1) -
酷,它奏效了。谢谢。但是如果我以后遇到这样的问题,你能解释一下为什么我的代码是错误的,而你的代码是正确的吗?