多列查找并返回下一列的相应值(最近值)

这是我想要完成的,我有两张纸:

参考表: 点击查看图像

Code Length Width Height A 78 48 25 B 78 48 34 C 12 7.4 5 D 12 15 5 E 12 15 7.5 F 12 15 9 G 24 15 5 H 24 15 7 

解决scheme表:

点击查看解决scheme示例

 Length Width Height Returning Code Match_L Match_W Match_H 10 6 8 C 12 7.4 5 

“返回代码”栏中的公式应查找相应参考表中最接近的值,即长度< – >长度,宽度< – >宽度,高度< – >高度,并从相应行中返回匹配的“代码”。

如果我想在值相等的时候匹配它,会更简单,但在我的情况下,它将在每个相应列中查找最接近的值(或者更大或者更小),并返回匹配的“代码”和Match_L,Match_W,Match_H列中的值。

任何帮助或指针,高度赞赏!

以下VBA将做这个工作。

 Sub LookupNearestValue() Dim ws As Worksheet: Set ws = Worksheets("Sheet1") Dim LastRow As Long: LastRow = ws.UsedRange.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row Dim i As Long, RowCounter As Long: RowCounter = 2 Dim tRowCounter As Long Dim tValue As Long Dim tempValue As Long Dim tLength As Long, tWidth As Long, tHeight As Long Dim tempLength As Long, tempWidth As Long, tempHeight As Long tLength = ws.Cells(2, 6) tWidth = ws.Cells(2, 7).Value tHeight = ws.Cells(2, 8).Value With ws For i = 2 To LastRow tempLength = ws.Cells(RowCounter, 2) tempWidth = ws.Cells(RowCounter, 3).Value tempHeight = ws.Cells(RowCounter, 4).Value tempValue = Abs(tLength - tempLength) + Abs(tWidth - tempWidth) + Abs(tHeight - tempHeight) If RowCounter = 2 Then tValue = tempValue tRowCounter = RowCounter ElseIf RowCounter > 2 And tempValue < tValue Then tValue = tempValue tRowCounter = RowCounter End If RowCounter = RowCounter + 1 Next i ws.Cells(2, 9) = ws.Cells(tRowCounter, 1) ws.Cells(2, 10) = ws.Cells(tRowCounter, 2) ws.Cells(2, 11) = ws.Cells(tRowCounter, 3).Value ws.Cells(2, 12) = ws.Cells(tRowCounter, 4).Value End With End Sub 

为了使这个macros的工作,你需要根据这些列安排在表单上的数据:

在这里输入图像说明

在我的工作表中,我已经设置在H2单元格中的值更改事件上运行此macros。

假设只有一个地方input所需的长度,宽度和高度,并且因此最多只有一个返回值:

在参考表中,在E到G中添加三列: length_difwidth_difheight_dif

这些列的公式将在单元格E2: =ABS(B2-SolutionSheet!A$2)然后将其展开到G2并将其绘制到解决scheme表的末尾。

在H: dif_abs参考表中添加另一列,其公式如下: =Sum(E2:G2)

然后返回您的值在您的SolutionSheet单元格D2中添加下面的公式: =Index(ReferenceSheet!$A$2:$H$9;MATCH(Min(ReferenceSheet!$H$2:$H$9);ReferenceSheet!$H$2:$H$9);1)