我想提取范围为“数据”的范围内的非空单元格的行索引(“A1:A10”),范围(“Ai”)(i
是偶数)具有值“ long“和range(”Aj“)(j
是奇数)是空单元格。如果我做得对,我应该得到(2,4,6,8,10),但我的代码失败了。这是我的代码:
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
我打印出来但结果让我感到困惑,我只得到了“2”(它可能是范围的行索引(“A2”)),我无法弄清楚原因。真的需要一些帮助。
答案 0 :(得分:0)
试试这个
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
经过测试,我在Range B
得到的结果是
2
4
6
8
10
如果您想使用现有代码,则需要更新以下行
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
旧的RowIndexes
未考虑1 to Number of NonEmptyRows
中的所有子变量,默认情况下它会选取第一个变量RowIndexes(1)
,其值为2