我有一个如下所示的Excel文件:
12123 51212
12123.5 45832
12124 37656
12124.5 32987
12125 42445
依此类推,其中列A总是增加0.5,而列B具有一定的输出。
现在我在单元格E2中有一个特定的值,例如12124,23,并且我想返回VBA代码,在这种情况下,最匹配的值在单元格A3中,因为我需要此单元格位置在进一步的代码中,我不需要B列中的相应值。但是,我不知道如何开始。该文件最多可以包含30000行。
我只想先知道要使用哪种方法,然后我将尝试自己编写代码:)
合资
您不必使用VBA来解决问题,Excel会做得很好!
尝试一下
=vlookup(E2;A:A;2;true)
以及您要尝试执行的操作,您必须以升序的方式对A列进行排序,否则会出现错误!
如果您确实需要在VBA中使用它,
一个简单的for + if结构,具有这样的测试
Function pr24(ByVal Value_To_Match As Double) As Range
For i = 2 To ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
If Cells(i, 1) > Value_To_Match Then
If Abs(Cells(i - 1, 1) - Value_To_Match) >= Abs(Cells(i, 1) - Value_To_Match) Then
pr24 = Range(Cells(i, 1))
Else
pr24 = Range(Cells(i - 1, 1))
End If
Exit For
Else
End If
Next i
End Function
或者您可以使用工作表函数Vlookup
Application.WorksheetFunction.VLOOKUP()
您需要首先对A列中的数据进行排序(从小到大),然后您可以使用简单的查找公式:=LOOKUP(E2,A:A)
如果您不想对数据进行排序,则可以像这样使用VBA循环-但这效率很低-您应该始终在可能的地方使用工作表公式:
Sub SO()
Dim resultCell As Excel.Range
Dim checkCell As Double
Dim bestDiff As Double
checkCell = Range("E2").Value
bestDiff = checkCell
For i = 1 To Range("A" & Rows.count).End(xlUp).Row
If Range("A" & i).Value <= checkCell Then
If (checkCell - Range("A" & i).Value) < bestDiff Then
bestDiff = checkCell - Range("A" & i)
Set resultCell = Range("A" & i)
End If
End If
Next i
MsgBox "Best match is in " & resultCell.Address
Set resultCell = Nothing
End Sub