搜索数组中的字符串时键入不匹配错误

时间:2013-08-21 19:07:53

标签: excel vba excel-vba

我正在开发一个宏,它将整合两个不同的订单数据来源。第一个来源将包含旧订单以及一些新订单,第二个来源将仅包含旧订单,并且将在手动更新的列中包含其他数据。

我的想法是从第二个来源获取订单总数,在第一个来源的订单总数之后将它们粘贴在一个工作表中,然后根据现有的订单编号搜索新文件中的所有订单编号跟踪器。我有一个for循环,它应该从新文件中找到尚未在跟踪器中的订单号,然后插入一个包含该订单详细信息的行。我在if语句上收到类型不匹配错误,检查字符串是否存在于数组中。请看一下这段代码:

Dim r As Integer
For r = 1 To 1000
    Dim NewOrd As String
    NewOrd = Range(Cells(r, 1), Cells(r, 1)).Value
    Dim ExistArray As Variant
    ExistArray = Range("a1", Range("a1").End(xlUp))
    Sheets("Sheet2").Select

    If IsEmpty(NewOrd) Then
        Exit For
    End If

    If Not UBound(Filter(ExistArray, NewOrd)) >= 0 And NewOrd <> "" Then
        Rows(r).Select
        Selection.Copy
        Sheets("Sheet3").Select
        Rows(r).Select
        Selection.Insert Shift:=xlDown
        Application.CutCopyMode = False
    End If
    r = r + 1
Next r

我尝试了几种不同的设置数组的方法,尝试添加显式选项,并尝试嵌套for循环(不是我最明亮的效率时刻)。非常欣赏另一双眼睛!

谢谢!

2 个答案:

答案 0 :(得分:2)

将一个Range对象分配给一个数组总是会产生一个二维数组,这会导致错误。

这样做:

ExistArray = Application.Transpose(Range("a1", Range("a1").End(xlUp)))

我认为应该为你解决。

<强>更新

您可能需要:

Dim ExistArray() As Variant

您的范围对象也存在问题,是单个单元格:

ExistArray = Application.Transpose(Array(Range("A1")))

答案 1 :(得分:0)

根据需要从“Sheet1”和“Sheet2”更改工作表名称:

Sub tgr()

    Dim wsNew As Worksheet
    Dim wsTracker As Worksheet
    Dim rIndex As Long

    'This is the sheet that contains the new data that needs to be added
    Set wsNew = Sheets("Sheet1")

    'This sheet contains the old data
    Set wsTracker = Sheets("Sheet2")

    'Go through each row in the new data
    For rIndex = 1 To wsNew.Cells(Rows.Count, "A").End(xlUp).Row

        'Verify that the row isn't blank and that it doesn't already exist in wsTracker
        If Len(wsNew.Cells(rIndex, "A").Value) > 0 And WorksheetFunction.CountIf(wsTracker.Columns("A"), wsNew.Cells(rIndex, "A").Value) = 0 Then

            'This is a new item that needs to be added
            'Copy the row to the next available row in wsTracker
            wsNew.Rows(rIndex).Copy wsTracker.Cells(Rows.Count, "A").End(xlUp).Offset(1)

        End If
    Next rIndex

    Set wsNew = Nothing
    Set wsTracker = Nothing

End Sub