2017-08-26 99 views
1

我想比較不同工作表兩列檢查,如果在A列中值在列B存在VBA - 運行時錯誤嘗試調換行看重

當我試圖轉當「13」行值並將其存儲到字典中以進行比較,則會觸發運行時錯誤「13」。

下面是代碼:

Sub Compare() 

Dim rngA As Range, rngB As Range 
Dim dict As Object, rw As Range 
Dim a As Application, tmp As String 
Dim Row1Last As Long 
Dim Row2Last As Long 

Set a = Application 
Set dict = CreateObject("scripting.dictionary") 
Set sht1 = Worksheets("list_Facility_BOS") 
Set sht2 = Worksheets("List_Facility_PG") 


With Sheets("list_Facility_BOS") 
Row1Last = .Cells(Rows.Count, "G").End(xlUp).Row 
End With 

With Sheets("List_Facility_PG") 
Row2Last = .Cells(Rows.Count, "H").End(xlUp).Row 
End With 

Set rngA = sht1.Range("G2:G" & Row1Last) 
Set rngB = sht2.Range("H2:H" & Row2Last) 

For Each rw In rngA.Rows 
    dict.Add Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)), rw.Row 
Next rw 

For Each rw In rngB.Rows 
    tmp = Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)) 
    If dict.exists(tmp) Then 
    Else 
     rw.Cells(1).Interior.ColorIndex = 3 
    End If 
Next rw 

End Sub 

我試圖反對另一個工作表中的另一個20K行列與一個20K行記錄列。錯誤「13」是觸發在這行代碼:

dict.Add Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)), rw.Row 

我是新來的卓越VBA編程,對不起,如果我could'nt解釋清楚。請讓我知道我的代碼是否有錯誤。

+0

如果行數多於excel有可能的列,轉置將失敗......) –

+0

@DirkReichel,你確定嗎?這似乎工作[最快的方式找到一個在行中在excel-range-excel-macro-vba](https://stackoverflow.com/questions/22685622/fastest-way-to-找到一個排功能於Excel的範圍內,使用-Excel的宏觀VBA/22704708#答案-22704708)。 @Dvid也許超過255個字符在一個單元格中[vba-scripting-dictionary-run-time-error-13-type-mismatch](https://stackoverflow.com/questions/17549379/vba-scripting-dictionary-run-時間錯誤-13型不匹配#答案-17817522)?如果不顯示錯誤的'rw.value'的值。 – BitAccesser

+0

@BitAccesser還沒有看到'對於rw.Rows中的每個rw'部分......這樣2^16的限制將永遠不會被打...但只有一列,'rw'只會是一個單元格因爲'rw.Value'不是一個數組,所以不能轉置。很明顯,如果閱讀整個代碼...(我應該更頻繁地這樣做):P –

回答

0

該函數的解釋丟失了,而複製了幾次。 這是我認爲的原始fastest-way-to-find-a-row-in-excel-range-using-excel-macro-vba

看一看評論

For Each rw In rngA.Rows 
    'Create a key from the entire row and map to row 
    ' If your rows are not unique you'll have to do a bit more work here 
    ' and use an array for the key value(s) 
    dict.Add Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)), rw.Row 
Next rw 

您需要rngA唯一行,或者你得到一個數組,導致錯誤13. 見Using-the-Dictionary-Class-in-VBA

可避免那樣的問題,使用一個數據庫而不是一個Excel文件。