返回用户定义范围内的行号而不是绝对行号

时间:2012-03-28 08:47:55

标签: excel vba excel-vba

我有范围rngData和数组aCopyrows() [int]

以下循环用于填充数组:

For Each c In rngData

    If c.Value = "Search term 1" Then
        aCopyrow(1) = c.Row
    ElseIf c.Value = "Search term 2" Then
        aCopyrow(2) = c.Row
    ElseIf c.Value = "Search term 3" Then
        aCopyrow(3) = c.Row
    End If

Next c

我希望数组存储与rngData对应的行号,或者换句话说:如果在rngData的第一行中找到匹配,则整数1存储在{{1}中}}。但是,使用此方法会存储该特定单元格的全局行号。

任何帮助表示赞赏!

aCopyrow只是给我一个错误(方法不受支持)。

2 个答案:

答案 0 :(得分:1)

怎么样:

aCopyrow(1) = c.Row  - rngData.Cells(1,1).Row + 1

如果有超过3个If,你可以像这样迭代以使代码更紧凑:

Dim i as Long

For Each c In rngData

    For i = 1 To 3
        If c.Value = "Search term " & i Then
            aCopyrow(i) = c.Row  - rngData.Cells(1,1).Row + 1
        End If
    Next i

Next c

答案 1 :(得分:0)

使用数据数组,速度会快得多:

Dim vArray As Variant

vArray = rngData.Value

For lRow = 1 To UBound(vArray, 1)
    For lCol = 1 To UBound(vArray, 2)
        If vArray(lRow, lCol) = "Search term 1" Then
            aCopyrow(1) = lRow
        ElseIf vArray(lRow, lCol) = "Search term 2" Then
            aCopyrow(2) = lRow
        ElseIf vArray(lRow, lCol) = "Search term 3" Then
            aCopyrow(3) = lRow
        End If
    Next lCol
Next lRow