跨多个列的INDEX MATCH用于大型数据集

时间:2019-06-06 15:50:58

标签: excel vba

我正在设置一些自动化,以在Excel中合并2个数据库。每行都有一个唯一的标识符(列C)。我已经编写了一些有效的代码,但是它笨拙又丑陋,无法适应更大的问题。

当前,代码循环遍历目标工作表中的行,并在找到结果时进行匹配。如果没有结果,它将使用错误跳过跳至下一列。它可以工作,但我希望能够在周围移动许多列,并为每列添加另一个重复行和错误处理程序不是很好。

任何提示都可以用来模拟DO While循环中的代码

Public Sub HistoryTransfer()

    Application.ScreenUpdating = False

    'copies last month's history information into this months RAG spreadsheet
    Dim HistoryWS As Worksheet
    Set HistoryWS = ActiveWorkbook.Sheets("RAG History")

    Dim RAGspreadsheet As Worksheet
    Set RAGspreadsheet = ActiveWorkbook.Sheets("RAG Spreadsheet")

    Dim lastRow As Integer
    lastRow = HistoryWS.Cells(Rows.Count, "A").End(xlUp).Row

    Dim RAGlastRow As Integer
    RAGlastRow = RAGspreadsheet.Cells(Rows.Count, "A").End(xlUp).Row

    Dim i As Integer
    i = 11
    Do While i < RAGlastRow
        On Error GoTo Errorhandler
        RAGspreadsheet.Range("Z" & i) = WorksheetFunction.Index(HistoryWS.Range("N11", "N" & lastRow), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
Errorskip:
        On Error GoTo Errorhandler2
        RAGspreadsheet.Range("AA" & i) = WorksheetFunction.Index(HistoryWS.Range("O11", "O" & lastRow), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
Errorskip2:
        On Error GoTo Errorhandler3
        RAGspreadsheet.Range("AB" & i) = WorksheetFunction.Index(HistoryWS.Range("P11", "P" & lastRow), Application.Match(RAGspreadsheet.Range("C" & i).Value, HistoryWS.Range("C11", "C" & lastRow), 0))
Errorskip3:
        i = i + 1
    Loop

Exit Sub

Errorhandler:
    Resume Errorskip:

Errorhandler2:
    Resume Errorskip2:

Errorhandler3:
    Resume Errorskip3:

    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

使用查找的示例,在帖子评论中描述(未试用):

arr = array("26", "27", "28") 'Z, AA, AB
For i = 11 to RAGlastrow
    Set rng = HistoryWS.Columns(3).Find(RAGspreadsheet.Cells(i,3).Value, lookin:=xlValues)
    If NOT rng = Nothing then
        For j = lbound(arr) to ubound(arr)
            RAGspreadsheet.Cells(i,arr(j)) = HistoryWS.Cells(rng.Row,arr(j)-12)
        Next j
    End If
Next i

还将重新陈述评论的第一句话:

Replace `WorkSheetFunction.` with `Application.` to trap the error.

这是由于每个人的行为而发生的。 WorksheetFunction将错误视为错误并停止代码,跳至调试模式。对于Application.,VBA会将错误分配为变量,然后转到下一个变量。


编辑1:前一天,Mat的马克杯对https://stackoverflow.com/a/56383812/1188513WorkSheetFunctionApplication的区别做了更好的解释(他的评论的复制链接)< / p>