這是我爲Excel編寫的一些VBA代碼。我試圖將Sheet1中的條目與Sheet2中的條目匹配。兩片材的結構如下:與Excel中的WorksheetFunction.Match()混搭
DATE | ID |
----- ----
Date1 ID1
Date2 ID2...
在我的代碼,我循環通過第一片的行,並設置從每個特定行的值作爲我MATCH()
查詢的一部分,在尋找這些的希望第二張相同的值。當我這樣做時,我想要MATCH()
返回找到這些值的行索引,所以我可以使用同一行從第一張表中輸入更多信息。此查詢使用多個條件,如value
和searchRange
變量所示(我試圖通過連接方法使用多個條件,如this文章中所見)。
問題是,我始終得到一個WorksheetFunction.Match無法使用的錯誤。當我使用一個標準(ID)時,該功能起作用。當我嘗試使用多個文件時,即使我按照前面鏈接文章中的說明操作,但仍然失敗。任何建議或想法來解決這個將不勝感激。
Sub runComparison(Sheet1 As String, Sheet2 As String)
Dim rowCount As Variant, columnCount As Variant, information As Variant
Dim counter As Integer
Dim value As String, searchRange As String
Sheets(Sheet2).Select
'Array of the number of rows in both sheets
rowCount = Array(Sheets(Sheet1).Cells(Rows.count, "A").End(xlUp).row, Sheets(Sheet2).Cells(Rows.count, "A").End(xlUp).row)
'Array of the number of columns in both sheets
columnCount = Array(Sheets(Sheet1).Cells(1, Columns.count).End(xlToLeft).Column, Sheets(Sheet2).Cells(1, Columns.count).End(xlToLeft).Column)
'The range in which we will look for the date and the ID
searchRange = CStr(Range(Cells(2, 1), Cells(rowCount(1), 1)).Address & "&" & Range(Cells(2, 2), Cells(rowCount(1), 2)).Address)
counter = 2
Do Until counter = rowCount(0)
'Sets the search term equal to the current cell in Sheet1
value = Sheets(Sheet1).Cells(counter, 1) & "&" & Sheets(Sheet2).Cells(counter, 2)
' Attempts to set the cell in the 8th column in the same row in which the search term is found equal to a certain value from the search term's row
Cells(WorksheetFunction.Match(value, searchRange, 0), 8) = Sheets(Sheet1).Cells(counter, columnCount(0)).value
counter = counter + 1
Loop
End Sub
編輯:下面是一些示例輸入
value = '7/14/2014&ESTUOUW1046465464'
searchRange = '$A2:$A298&$B2:B298'
非常感謝反饋,但範圍並非來自A2:B298 - 它是兩個範圍與&符號組合在一起,每個範圍都是整列。我這樣做是因爲我正在處理多個標準,就像上面鏈接的文章中所述。我只是試圖複製同樣的行爲 - 這裏的鏈接到什麼我談論:http://support.microsoft.com/kb/59482 – jkayani
那麼這本文適用於工作表上的功能*還特意請注意,您必須以*數組函數*的形式輸入此函數。現在,你既不做也不做!讓我看看我是否可以在VBA中完成這項工作:) –
該公式還使用'Index'函數作爲數組公式的一部分,您也沒有這樣做。我不認爲這部分是需要的......將很快更新。 –