我如何遍历数组和数组

时间:2019-07-09 23:04:51

标签: excel vba

我正在尝试在代码中创建一个循环,以针对“ Circs”字符串变量(由用户定义)检查数组列表(其中存储有字符串),如果该字符串存在,则返回true值在任何数组中。

使用了Debug和其他SO答案来尝试了解正在发生的事情。尝试使用Array()功能,其中CircsG1 = Array()......仅导致错误显示在行For j = 1 To UBound(ListofArrays(i))上。

Private Sub ComboBox2_Change()
''When S&S Circumstance selection is made

Dim WS As Worksheet

Set WS = ThisWorkbook.Sheets("Administration")

''Arrays where strings are stored
Dim CircsG1 As Variant
Dim CircsG2 As Variant
Dim CircsG3 As Variant
''Array of Array
Dim ListofArrays As Variant

''String to compare against
Dim Circs As String


Dim i As Integer
Dim j As Integer
Dim NoOfArr As Integer

NoOfArr = 3

CircsG1 = WS.Range("P2:P19").Value
CircsG2 = WS.Range("Q2:Q7").Value
CircsG3 = WS.Range("R2:R5").Value
ListofArrays = Array(CircsG1, CircsG2, CircsG3)

Circs = Me.ComboBox2.Value

For i = 1 To NoOfArr
    For j = 1 To UBound(ListofArrays(i))
        If InStr(ListofArrays(i, j), Circs) Then
            MsgBox ListofArrays(i)
''and some other code
        Else
        Exit Sub
        End If
    Next
Next

Skip:
End Sub

使用SO上的其他各种答案调查了我的代码后,我发现了几件事。

  1. UBound(ListofArrays(i))返回的值小于它正在查看的数组中存储的字符串数。即我定义的范围意味着该值应为17,但返回值为6。

  2. 运行时错误9,第If InStr(ListofArrays(i, j), Circs) Then行的下标错误

2 个答案:

答案 0 :(得分:2)

您在这里处理两个不同的依据。您的ListofArrays的底数为0,假设您没有修改模块的任何基本选项,但是其他数组的底数为1,因为您是从工作表中提取数据的。

现在我们已经确定,在数组中为数组建立索引时会遇到语法问题。

ListofArrays只是一维的,但是您像二维数组一样使用它:

InStr(ListofArrays(i, j), Circs)

此外,当您从工作表中提取数据并将其放入数组中时,实际上是在创建二维数组(因为工作表是二维的)。您仅从该数组中提取一列数据,因此可以对第二维使用(j, 1)

这是访问数组中数组的正确方法:

Dim i as long, j as long

For i = 0 to Ubound(ListofArrays)
    for j = 1 to Ubound(ListofArrays(i))

        If InStr(ListofArrays(i)(j, 1), Circs) Then MsgBox ListofArrays(i)(j, 1)

    next j
next i

要完全避免“基本问题”,只需使用LBound()

Dim i as long, j as long

For i = lbound(ListofArrays) to Ubound(ListofArrays)
    for j = LBound(ListofArrays(i)) to Ubound(ListofArrays(i))

        If InStr(ListofArrays(i)(j, 1), Circs) Then MsgBox ListofArrays(i)(j, 1)

    next j
next i

答案 1 :(得分:0)

VBA中的数组从零[1]开始索引。因此,为什么会有错误。例如,应该为:

For i = 0 To NoOfArr-1

因此,您将需要重写循环和索引,或更改数组声明。但是,最简单最简单的解决方案(无需更改现有代码)是在模块顶部添加以下行:

Option Base 1 

这确保数组被1索引。