“For Each x In arr”中的错误只是一个条目

时间:2018-05-17 09:53:55

标签: excel vba excel-vba

我使用For循环仅查找新数据并将其移动到另一张表,但是当只有一行输入时它会停止并引发错误。它停在“For each x in arr”中,“arr”则等于那一个输入。

Dim arr As Variant
arr = Range("K2:K" & Cells(Rows.Count, "K").End(xlUp).Row).Value
Dim x As Variant, y As Variant, match As Boolean
For Each x In arr
    match = False
    For Each y In varr
        If x = y Then match = True
    Next y
    If Not match Then
        Sistaraden = Sheets("Sammanställning").Cells(Rows.Count, "A").End(xlUp).Row + 1
        Sheets("Sammanställning").Range("A" & Sistaraden).Value = x
        'varr = Sheets("Sammanställning").Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
    End If
Next x

2 个答案:

答案 0 :(得分:2)

首先检查行数:

Dim arr() As Variant, lRow as Long
lRow = Cells(Rows.Count, "K").End(xlUp).Row
If lRow > 2 then
   arr = Range("K2:K" & lRow).Value
Else
   Redim arr(1 to 1, 1 to 1)
   arr(1, 1) = Range("K2").Value
End If
Dim x As Variant, y As Variant, match As Boolean
For Each x In arr

答案 1 :(得分:0)

使用Option Explicit它可以帮助您查看代码中varrarr之间的差异。

然后使用此行制作数组:

arr = Application.Transpose(Range("K2:K" & Cells(Rows.Count, "K").End(xlUp).Row))

Application.Transpose可帮助您制作超出范围的1维数组。它可以很容易地循环。