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

时间:2017-08-15 07:18:23

标签: excel excel-vba multiple-columns roundup vba

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

参考表: Click to see the image

Length    Width   Height  Returning Code   Match_L   Match_W   Match_H

 10        6       8         C                12        7.4        5

解决方案表:

Click to see solution example

{{1}}

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

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

非常感谢任何帮助或指示!

2 个答案:

答案 0 :(得分:1)

假设只有一个地方可以输入所需的长度,宽度和高度,因此最多只返回一个值:

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

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

使用以下公式在H:dif_abs的参考表中添加另一列:=Sum(E2:G2)

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

答案 1 :(得分:1)

以下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

要使此宏工作,您需要根据这些列安排在工作表上显示数据:

enter image description here

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