以下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
爲了讓這個宏的工作,你需要根據這些列安排對錶中的數據:
在我的表,我已經安裝上運行值的變化情況下,本宏在H2
單元格中。
你已經嘗試過什麼,並且哪裏失敗?你在找VBA的解決方案嗎?如果是的話,你已經有了什麼代碼?兩個方向的差異是否平等對待,就像絕對差異一樣,或者甚至可以相互影響? – Luuklag
您有兩張工作表,在這張工作表中,您將輸入'ReturningCode',其餘值將自動從另一張工作表填充。這樣對嗎?請多說明一下,輸入是什麼以及預期的輸出是什麼。 –
@MIdrees我將輸入長度,寬度和高度,它應該返回「代碼」。在這個例子中,我輸入了L = 10,W = 6,H = 8,並且最接近的匹配值在「C」中,L = 12,= 7.4,H = 5。所有三個值都應該匹配! –