Display Row Values based on Nearest Numeric Match of Key

跟風遠走 提交于 2020-01-17 05:14:05

问题


Say I have a sorted list of values in column A. They serve as a 'key' to each numerical row. Something like this:

   ___A_(key)_______B______         ______G_____
1 |____2.58___|____________|   ... |____________|   ... 
2 |____2.69___|____________|   ... |____________|   ...
        ...         ...                  ...
   ________________________         ____________
x |____5.69___|____________|   ... |____________|   ...

Columns B through G have some values for each of the keys, so it's basically a 2D spreadsheet of numerical data.

I need to be able to quickly access a certain row by the approximate value.

Right now I have set a Filter on the column, and can search for the rows, but for that I need to enter the key value exactly, i.e. 2.58, or 2.69, but not something like 2.64.

I want to be able to enter something like 2.64, and have the row with nearest key value be shown to me, preferably in a separate location, such as on the side of the table, like starting in column I where exactly can be defined, but basically any method where I type in a value and get conveniently shown the row values will do. How can I do this?

My experience level is: I did some simple stuff in VBA/excel ~10 years ago... and basically looking for a good starting direction and approach.


回答1:


Assuming your Data is in A1:A20 and your look up value is in B1 this formula will return the closest:

=INDEX(A1:A20,MATCH(MIN(ABS(A1:A20-B1)),ABS(A1:A20-B1),0))

When entering make sure to press Ctrl + Shift + Enter and NOT just Enter.

It is getting the smallest difference then returning its row into the index, index then returns the value.




回答2:


This is what I'm thinking, You loop through all the rows and get the difference between your target and the value in that cell. You find the row that gives the least difference and that will be your target row.

Dim dblErr As Double
Dim intIndex As Integer
Dim i As Integer
Dim dblTarget As Double

dblTarget = 'Value you are after
dblErr = 10000 ' or some other large number
For i = 1 To x 'x= number of rows
    If dblErr > Abs(Cells(i + 1, 1) - dblTarget) Then
        dblErr = Abs(Cells(i + 1, 1) - dblTarget)
        intIndex = i
    End If
Next i

Ans = Cells(intIndex, 1)


来源:https://stackoverflow.com/questions/21918877/display-row-values-based-on-nearest-numeric-match-of-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!