2013-08-21 26 views
0

我正在研究將合併兩個不同的訂單數據源的宏。第一個來源將包含舊訂單以及一些新訂單,第二個來源將僅包含舊訂單,並將在手動更新的列中包含其他數據。在數組中搜索字符串時類型不匹配錯誤

我的想法是從第二個來源獲得訂單總計,將它們粘貼到來自第一個來源的訂單總計之後的工作表中,然後根據來自第二個來源的訂單號從新文件中搜索所有訂單號現有的跟蹤器。我有一個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 

我已經嘗試設置陣列的幾個不同的方法,嘗試添加選項明確,並試圖嵌套循環(不是我最亮的時刻效率)。將不勝感激另一套眼睛!

謝謝!

回答

2

將Range對象分配給數組總是會導致導致錯誤的二維數組。

這樣做:

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

我認爲,應該解決它。

更新

您可能需要:

Dim ExistArray() As Variant 

您的範圍對象也是有問題的,是一個單細胞:

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

不幸的是它沒有。代碼在同一行(如果不是UBound ...)中出現相同的錯誤。 – ExcelMacroStudent

+1

是的,範圍(「a1」,範圍(「a1」)。結束(xlUp))'產生單個值。第二次使用「a1」需要在tigeravatar的代碼中使用「a1000」或者「.Rows.Count」。 –

+0

您的範圍對象是問題所在。 –

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