在2D Array Excel VBA中查找空白条目的索引

时间:2016-11-30 12:17:40

标签: arrays vba excel-vba execl excel

我有一个2D数组Dim Line_Qty(6, 2),其值如下:

**Date      Line_No  Quantity**

2016-11-15   1       5856

2016-11-15   2       5451

2016-11-15   3       5499

2016-11-15      

2016-11-15      

2016-11-15      

我想要找到的是第一个空白的索引Line_Qty(4, 1)

这样做的目的是我在excel表中粘贴这些值,我想停止粘贴直到数量的最后一个条目。

我的粘贴代码就是这个

For i = 0 To 6
For j = 0 To 2

Worksheets("DY_SET").Cells(i + 1, j + 1).Value = Line_Qty(i, j)
Worksheets("DY_SET").Range("A" & i + 2).NumberFormat = "yyyy-mm-dd"

Next j
Next i

希望我清楚明白,并提前感谢

2 个答案:

答案 0 :(得分:1)

当某个数组值为空时,此代码转义循环。这就是你需要的吗?

For i = 0 To 6
    For j = 0 To 2
        If Line_Qty(i, j) = "" Then Exit For
        Worksheets("DY_SET").Cells(i + 1, j + 1).Value = Line_Qty(i, j)
    Next j
    Worksheets("DY_SET").Range("A" & i + 2).NumberFormat = "yyyy-mm-dd"
Next i

答案 1 :(得分:1)

你可以先"截断"数组,然后粘贴幸存的值,如下所示:

Dim Line_QtyCopy(0 to 6, 0 to 2) As Variant

' search Line_Qty first row with empty qty
For i = 0 To 6
    If Line_Qty(i, 2) = "" Then Exit For
Next i

With Worksheets("DY_SET").Range("A1") '<--| reference target range
    If i <7 Then '<--| if found empty qty before reaching array end
        i = i - 1 '<--| update row index to last not emoty one
        ReDim Line_QtyCopy(0 to i, 0 to 2) '<--| size a new array to the number of rows
        ' fill it up to last not empty qty in Line_Qty
        For i = 0 To i
            For j = 0 To 2
                Line_QtyCopy(i,j) = Line_Qty(i, j)
            Next
        Next
        .Resize(i).Value = Line_QtyCopy '<--| write it down from cell A1
    Else
        .Resize(6).Value = Line_Qty
    End If
End With