VBA查找最近的值

时间:2018-09-20 14:09:12

标签: excel vba logic

我有一个包含12列(相隔3列)的电子表格,其中列出了一堆数字值。我想知道对这些进行排序以找到具有最接近0.5值的单元格的最佳方法是什么。

在这种情况下,Vlookup是否可以有效工作?还是最好通过某种测试循环遍历这些值?

3 个答案:

答案 0 :(得分:0)

import pandas as pd
import pyodbc

server = 'server'
db = 'db'
conn_sql = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes')

sql_query = "SELECT your_data FROM your_table"

df = pd.read_sql(sql_query, conn_sql)

答案 1 :(得分:0)

使用此:

=INDEX(B:B,AGGREGATE(15,6,ROW(B2:B21)/(AGGREGATE(15,6,ABS($C$2:$C$21-0.5),1)=ABS($C$2:$C$21-0.5)),1))

然后拖动。

http://php.net/manual/en/class.domxpath.php

答案 2 :(得分:0)

您必须将其放置在VBE编辑器的新模块中,只需在代码下面指定您的工作表名称。它会在每列底部下方2行打印每列的结果。

Sub checker()

Dim row As Long
Dim lastrow As Long
Dim col As Integer
Dim dif As Double
Dim minRow As Long: minRow = 1
Dim startRow

With ThisWorkbook.Worksheets("Enter your sheet name")

' change 1 to 2 below if your first row is a header not a data value
startRow = 1

' starting at col D
For col = 4 to 4 + (3*12) Step 3

    dif = Abs(.Cells(startRow, col) - .5)
    lastRow = .Cells(.Rows.Count, col).End(xlUp).Row

    For row = startRow To lastRow
        If Abs(.Cells(row, col).Value - .5) < dif Then
            dif = Abs(.Cells(row, col).Value - .5)
            minRow = row
        End If
    Next

    ' print result at bottom of ea row
    .Cells(lastRow + 2, col).Value = "Row: " & minRow & ", dif: " & dif & ", value: " & .Cells(minRow, col).Value

Next

End With

End Sub

祝你好运