[英]Extract row indexes of non-empty cells in specific range
I want to extract row indexes of non-empty cells in range("A1:A10") which has a name "data", range("Ai") ( i
is even number) has value "long" and range("Aj") ( j
is odd number) is empty cell. 我想提取名称为“ data”的range(“ A1:A10”)中非空单元格的行索引,range(“ Ai”)( i
为偶数)的值为“ long”和range(“ Aj “)( j
为奇数)是空单元格。 If I do it right I should get (2,4,6,8,10), but my code failed. 如果我做对了,我应该得到(2,4,6,8,10),但是我的代码失败了。 Here is my code: 这是我的代码:
Sub RowIndexes()
Dim NonEmptyRows As Integer
Dim RowIndexes() As Integer
Dim i As Integer
Dim rng As Range
NonEmptyRows = WorksheetFunction.CountIf(Range("data"), "long")
ReDim RowIndexes(1 To NonEmptyRows)
For Each rng In Range("data")
If rng.Value = "long" Then
i = i + 1
RowIndexes(i) = rng.Row
End If
Next rng
Sheets("sheet1").Range("B1:B5").Value = RowIndexes
End Sub
I printed it out but the result confused me, I just got "2" (it may be the row index of range("A2")) and I can't figure out why. 我将其打印出来,但结果使我感到困惑,我只得到了“ 2”(可能是range(“ A2”)的行索引),我不知道为什么。 Really need some help here. 真的需要一些帮助。
Try This 尝试这个
Dim i As Integer
Dim rng As Range
For Each rng In Range("data")
If rng.Value = "long" Then
i = i + 1
Sheets("sheet1").Range("B" & (Range("B" & Rows.Count).end(xlUp).Row+1)).Value = rng.Row
End If
Next rng
Tested and the results I got in Range B
was 经过测试,我在Range B
中得到的结果是
2
4
6
8
10
If however you want to use your existing code then you need to update the following lines 但是,如果您想使用现有代码,则需要更新以下几行
OLD LINE 旧线
Sheets("sheet1").Range("B1:B5").Value = RowIndexes
NEW EDITED LINES 新的编辑行
For i = 1 To NonEmptyRows
Sheets("sheet1").Range("B" & (Range("B" & Rows.Count).End(xlUp).Row + 1)).Value = RowIndexes(i)
Next i
The old RowIndexes
does not account for all the sub variables as in 1 to Number of NonEmptyRows
it by default picks up the first variable which is RowIndexes(1)
whose value is 2
旧的RowIndexes
并未考虑所有子变量,因为默认情况下它会选择第一个变量RowIndexes(1)
其值为2
1 to Number of NonEmptyRows
因此它不会默认1 to Number of NonEmptyRows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.