vba - 在 VBA 中重新定义数组

标签 vba excel

我在 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

最佳答案

这是因为你无法改变第二个维度的下限,你需要保持它不变..

您在顶部声明 ReDimdistinctList(0 To 1, 0 To j)

重调时,需要将第二个维度的下限保持在0

ReDim Preserve distinctList(0 To 1, 0 To UBound(distinctList, 2) + 1)

关于vba - 在 VBA 中重新定义数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855289/

相关文章:

vba - 如何使用 Excel VBA 获取 Windows 应用程序进程主窗口标题和窗口状态属性?

excel - 循环中的单元格地址

vba - 从 excel vba 到 Access DB 的多个同时连接

excel - 使用 VBA 在用户窗体上生成组合框和编辑文本框

excel - 如何使用 VBA 获取谷歌搜索的第一个搜索结果链接?

excel - 如何在文本输入期间自动调整 Excel 中的列宽

excel - 将字典 ByRef 传递给 excel VBA 用户窗体模块中的私有(private)子会给出 ByRef 类型不匹配错误

vba - 获取 msoFileDialogFolderPicker 的初始路径

vba - 运行时错误 35788。调用 Windows 日期和时间选择器控件时发生错误

excel - PYQT4无法写入excelwriter