从下面的代码中可以看到,我将循环一个数组,如果满足条件,我想获取包含A列中特定值的行号。
图片:
Option Explicit
Sub test()
Dim i As Long, arr As Variant
With ThisWorkbook.Worksheets("Sheet1")
arr = .Range("A1:A10")
For i = LBound(arr) To UBound(arr)
If arr(i, 1) = 4 Then
'Get the row that the array value apperas in Column A. The answer should be row number 8
End If
Next i
End With
End Sub
答案 0 :(得分:4)
您的数组通过i
与您的行号相关,尽管这取决于从第一行开始的数组。如果您从第5行开始,它将是i + 4
For i = LBound(arr) To UBound(arr)
If arr(i, 1) = 4 Then
Debug.Print i
End If
Next i
答案 1 :(得分:2)
Sub test()
Dim i As Long, arr As Variant, rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
arr = rng.Value
For i = LBound(arr) To UBound(arr)
If arr(i, 1) = 4 Then
Debug.Print rng(i).Row
End If
Next i
End Sub
答案 2 :(得分:1)
尝试使用以下每个单元格。它将返回完全匹配的行。
Option Explicit
Sub test()
Dim i As Long
Dim cells As Range
With ThisWorkbook.Worksheets("Sheet1")
For Each cells In .Range("A1:A10")
If cells.Value = 4 Then
MsgBox ("row Number is :" & cells.Row)
End If
Next
End With
End Sub
答案 3 :(得分:0)
我添加了一个变量,用于存储范围开始处的初始行号。
此外,请注意,数组的索引 i 与范围内的位置有关。当您执行arr = .Range("A1:A10")
时,您将创建一个10个单元格(10x1)的BIDIMENSIONAL数组。索引1为Cell(1,1),索引2为Cell(2,1),依此类推。
因此,这里的技巧是在范围开始的地方存储行号,然后汇总索引。
Sub test()
Dim i As Long, arr As Variant
Dim rng As Range
Dim InitialRow As Long
With ThisWorkbook.Worksheets("Sheet1")
Set rng = .Range("A1:A10")
arr = rng.Value
InitialRow = Range(Left(rng.Address(False, False), Application.WorksheetFunction.Search(":", rng.Address(False, False)) - 1)).Row
For i = LBound(arr) To UBound(arr)
If arr(i, 1) = 4 Then
'Get the row that the array value apperas in Column A. The answer should be row number 8
Debug.Print InitialRow + i - 1 'this is the row number that matches the value
End If
Next i
Erase arr
End With
End Sub
如果我使用`Range(“ A1:A10”)上的值对此进行测试,则会得到结果8。
但是如果我更改值的位置,我也会用相同的代码得到另一个结果,因为代码存储了范围的初始行。
如果您的范围永远不会改变,则仅使用索引即可。但是,如果范围不会总是在同一行开始,那么您需要知道第一行并将其与索引相加。
希望此代码可以帮助您并适应您的需求。