vba, 同一列里,给单元格找到与其值一样最近的单元格所在行数, 从上往xia的方向
时间: 2023-09-13 08:03:07 浏览: 128
你可以使用以下代码实现:
```vb
Function findClosestMatchRow(rng As Range) As Integer
Dim targetValue As Variant
Dim minDiff As Double
Dim currDiff As Double
Dim matchRow As Integer
Dim currRow As Integer
targetValue = rng.Value
minDiff = 99999 ' set a large initial value for minDiff
For currRow = rng.Row - 1 To 1 Step -1 ' search upwards from the current row
currDiff = Abs(targetValue - Cells(currRow, rng.Column).Value)
If currDiff < minDiff Then ' found a closer match
minDiff = currDiff
matchRow = currRow
End If
Next currRow
findClosestMatchRow = matchRow ' return the row number of the closest match
End Function
```
将这段代码复制到你的 VBA 模块中后,你可以在 Excel 中使用类似于以下公式的方式调用该函数:
```
=findClosestMatchRow(A1)
```
其中,A1 是你要查找最近匹配行号的单元格。该函数将返回与该单元格值最接近的单元格所在的行号,从上往下数。
阅读全文