简体   繁体   English

Excel VBA 自动查找数字的上限和下限

[英]Excel VBA finding the upper and lower bound of a number automatically

值列表

I am trying to find the upper and lower bound of a number by using Excel VBA but I have no idea how to write the code for that.我试图通过使用 Excel VBA 找到数字的上限和下限,但我不知道如何编写代码。 So for example, I am given the number 35 (Cell E6).例如,我得到了数字 35(单元格 E6)。 And in the list of values (in column A) that I am given, I want the program to automatically find 30 and 40 respectively and store the values beside 30 and 40 in 2 variables for some further calculations.在我给出的值列表(在 A 列中)中,我希望程序分别自动找到 30 和 40,并将 30 和 40 旁边的值存储在 2 个变量中以进行进一步计算。 Is that possible?那可能吗? Thanks a lot in advance:)提前非常感谢:)

If you have Office 365, that would be a good occasion to use the brand new Excel XLOOKUP function which is also available in VBA.如果您有 Office 365,那将是使用全新 Excel XLOOKUP function 的好时机,它也可用于 VBA。

For example:例如:

Dim wb As Workbook
Set wb = Workbooks("MyWorkbook.xlsm")

Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet1")

Dim LowerBound As Long
Dim UpperBound As Long

With ws
    LowerBound = WorksheetFunction.XLookup(.Range("E6"), .Range("$A$1:$A$1000"), .Range("$A$1:$A$1000"), CVErr(xlErrValue), -1, 1)
    UpperBound = WorksheetFunction.XLookup(.Range("E6"), .Range("$A$1:$A$1000"), .Range("$A$1:$A$1000"), CVErr(xlErrValue), 1, 1)
End With

Debug.Print LowerBound
Debug.Print UpperBound

More details on how to use XLOOKUP 有关如何使用 XLOOKUP 的更多详细信息

The key here is to use the 5th argument of the function (match mode) to your advantage.这里的关键是使用 function(匹配模式)的第 5 个参数来发挥您的优势。 To get the "lower bound" we ask for the exact match or next smaller and for the "upper bound" we ask for the exact match or next larger.为了获得“下限”,我们要求完全匹配或下一个更小,而对于“上限”,我们要求完全匹配或下一个更大。

在此处输入图像描述

Caveats and notes:注意事项和注意事项:

  • In the code above, the lookup_array and the return_array ranges are hardcoded, but it would be better to simply define a range object and refer to it instead.在上面的代码中, lookup_arrayreturn_array范围是硬编码的,但最好简单地定义一个范围 object 并引用它。

  • If the lookup_value is greater than the biggest number in the lookup_array , it will give you a run-time error or the returned value will be 0.如果lookup_value大于lookup_array中的最大数字,它将给您一个运行时错误或返回值为 0。

  • Make sure you have the Immediate Window visible (Ctrl+G) if you want to see the results of the Debug.Print statements.如果您想查看Debug.Print语句的结果,请确保立即看到 Window (Ctrl+G)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM