在数组中搜索字符串并存储它出现的行号?

时间:2016-12-07 18:53:04

标签: arrays vba excel-vba search excel

我见过几个类似的问题,但没有一个是完全一样的!

我有一个相当大的数组没有重复两个值。 我需要在数组中搜索某个字符串,然后将行号存储在字符串所在的位置。

这将进行多次,所以如果可能的话,“最快”的方式将不胜感激!

例如 数组:

   1  2  3
   4  5  6
   7  8  9

说我想找“8”。代码应搜索矩阵,发现它在第3行并将“2”存储到变量中(或“3”取决于是否包含选项库1)。

在我的情况下,我正在寻找的值只会出现在一列上,所以我不需要搜索整个数组。

非常感谢。

编辑: 抱歉,我没有ediquette!这是我的第一篇文章。以下是我到目前为止的情况:

col=3
For row = 1 to 50
  if searchterm = Matrix(row,col).value Then
    searchrow=row
    exit for
  end if
Next row

有更有效的方法吗?

1 个答案:

答案 0 :(得分:0)

阵列本质上很快。此函数将返回索引数组。如果未找到查找值,则返回值将为空。

用法

indices = getValueIndices(8, DataArray)

If not isEmpty(indices) then
    x = indices(0)
    y = indices(1)
End if

功能

Function getValueIndices(Value As Variant, DataArray As Variant) As Variant
    Dim x As Long, y As Long
    Dim is2d As Boolean
    Dim v As Variant
    x = LBound(DataArray, 1)

    On Error Resume Next
    is2d = UBound(DataArray, 2)
    On Error GoTo 0

    If is2d Then y = LBound(DataArray, 2)

    For Each v In DataArray
        If v = Value Then
            If is2d Then
                getValueIndices = Array(x, y)
            Else
                getValueIndices = Array(x)
            End If
            Exit Function
        End If
        x = x + 1
        If x > UBound(DataArray, 1) Then
            x = LBound(DataArray, 1)
            y = y + 1
        End If
    Next

End Function

测试

Sub Test()
    Dim DataArray As Variant

    'Test 1D Array - Base 0
    DataArray = Array(1, 2, 3, 4, 5, 6, 7, 8)
    Debug.Print "Test 1D Array - Base 0: "; getValueIndices(8, DataArray)(0)

    'Test 2D Array - Base 1
    DataArray = [{1,2,3;4,5,6;7,8,9}]
    Debug.Print "Test 2D Array - Base 1:"; getValueIndices(8, DataArray)(0), getValueIndices(8, DataArray)(1)

    'Test 2D Array - Base 0
    ReDim DataArray(0 To 2, 0 To 2)
    DataArray(0, 0) = 1: DataArray(0, 1) = 2: DataArray(0, 2) = 3
    DataArray(1, 0) = 4: DataArray(1, 1) = 5: DataArray(1, 2) = 6
    DataArray(2, 0) = 7: DataArray(2, 1) = 7: DataArray(2, 2) = 8
    Debug.Print "Test 2D Array - Base 0: "; getValueIndices(8, DataArray)(0), getValueIndices(8, DataArray)(1)
    Debug.Print "Test IsEmpty with Bad Value: "; IsEmpty(getValueIndices(100, DataArray))

End Sub

结果

enter image description here