1

VBA で 2 次元配列のサイズを変更する際に深刻な問題があります。私はこの (人気のある) 問題について多くのことを読みましたが、コードの何が問題なのかまだわかりません。

だから、私はスプレッドシートにいくつかのデータを持っています。2 行目には要素の説明があり、1 行目にはそれらの要素のカテゴリがあります。私がやりたいことは、最初の行に (異なる) カテゴリがあり、2 行目に特定のカテゴリに関連する説明のインデックスがある配列を作成することです。コードは If j = UBound(distinctList, 2) Then Then 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
4

2 に答える 2

2

これは、2 番目の次元の下限を変更できないためです。同じ値を維持する必要があります。

ReDim distinctList(0 To 1, 0 To j)あなたはトップで宣言します

再調整するときは、2 番目の次元の下限を0

ReDim Preserve distinctList(0 To 1, 0 To UBound(distinctList, 2) + 1)
于 2013-11-08T09:44:50.510 に答える