VBA'Vlookup'函数在dynamic行数上运行

我不知道如何将一个函数和一个子函数结合起来。 最有可能的是,我有以下需要更正。

我在两个单独的表中有两个表格:Sheet1和Sheet2。

两个表都有dynamic的行数,但是第一行总是在同一个地方开始,两个表中的列数也是不变的。 Sheet1数据在A2中开始,在R2中结束:R和Sheet2数据从A3开始,到H3:H结束。

我试图在Sheet1的列O中实现VLOOkUP,这将填充Sheet1的列O中的每个单元格与Sheet2中列D的相关值。 到目前为止,我设法提出了如下代码。

Public Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String Dim s As String On Error Resume Next s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False) If IsError(s) Then fsVlookup = "" Else fsVlookup = s End If End Function Public Sub Delinquency2() Dim ws1 As Worksheet, ws2 As Worksheet Dim rng As Range Dim rCell As Range Set ws1 = Worksheets("Sheet1") Set ws2 = Worksheets("Sheet2") pSearch = ws1.Range("D2:D" & Cells(Rows.Count, "A").End(xlDown).Row) pMatrix = ws2.Range("$A3:$H" & Cells(Rows.Count, "C").End(xlDown).Row) pMatColNum = 4 Set rng = ws1.Range("O2:O" & Cells(Rows.Count, "A").End(xlDown).Row) For Each rCell In rng.Cells With rCell rCell.FormulaR1C1 = s End With Next rCell End Sub 

你将需要使用下面的类似的行来调用你的子函数。 然后它从你的sub中取出你的值,并把它们input到函数中并返回值。

您需要调暗范围以便在function中正确识别它们。 我已经更新了你的代码,使其工作,你可以摆弄它,使其按照你想要的方式工作。 我还更新了一些其他的点来找出正确的范围,你不想在你使用xlDown地方使用它,导致一个巨大的循环覆盖你不想要的单元格。

 Public Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String Dim s As String On Error Resume Next s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False) If IsError(s) Then fsVlookup = "" Else fsVlookup = s End If End Function. Public Sub Delinquency2() Dim ws1 As Worksheet, ws2 As Worksheet Dim rng As Range Dim rCell As Range, pMatrix As Range Set ws1 = Worksheets("Sheet1") Set ws2 = Worksheets("Sheet2") pSearchCol = ws1.Range("D2:D2").Column Set pMatrix = ws2.Range("$A3:$H" & ws2.Cells(Rows.Count, "C").End(xlUp).Row) pMatColNum = 4 Set rng = ws1.Range("O2:O" & ws1.Cells(Rows.Count, "A").End(xlUp).Row) For Each rCell In rng.Cells With rCell rCell.Value = fsVlookup(ws1.Cells(rCell.Row, pSearchCol), pMatrix, pMatColNum) End With Next rCell End Sub