Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 提取特定范围内非空单元格的行索引_Vba_Excel - Fatal编程技术网

Vba 提取特定范围内非空单元格的行索引

Vba 提取特定范围内非空单元格的行索引,vba,excel,Vba,Excel,我想提取名称为“data”的区域(“A1:A10”)中非空单元格的行索引,区域(“Ai”)(I为偶数)的值为“long”,区域(“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 N

我想提取名称为“data”的区域(“A1:A10”)中非空单元格的行索引,区域(“Ai”)(
I
为偶数)的值为“long”,区域(“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”)),我不知道为什么。这里真的需要帮助。

试试这个

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
经过测试,我在
范围B
中得到的结果是

2
4
6
8
10
但是,如果要使用现有代码,则需要更新以下行

旧的

Sheets("sheet1").Range("B1:B5").Value = RowIndexes
新编辑的

For i = 1 To NonEmptyRows
    Sheets("sheet1").Range("B" & (Range("B" & Rows.Count).End(xlUp).Row + 1)).Value = RowIndexes(i)
   Next i

旧的
行索引
没有考虑所有的子变量,因为
1到非空行数
默认情况下,它会选择第一个变量,即
行索引(1)
,其值为
2

,感谢您的指导,我修复了这个将项目推迟两天的问题。在你的启发下,我进一步挖掘了一下,发现了一些有趣的东西。如果你创建了一个数组并手动为其分配了一些值,请使用勾号接受答案,它似乎是“行向量”,如果你想打印出来,可以使用Range(“whatever”).value=worksheetfunction.transpose(MyArray)或for循环。但如果您将范围值传输到数组,它似乎是“列向量”或“矩阵”,您可以使用range(“任意”)。value=MyArray(它们具有相同的行和列)将其打印出来。我想知道是否有一个普遍的模式?