FindNext-VBA代码测试正确,但是Excel中的公式不起作用

时间:2018-07-15 10:02:31

标签: excel vba

我不是VBA的专家,如果我的问题不清楚,抱歉。我们编写了一个代码,该代码在Module中进行测试时可以运行并给出正确的结果。但是,在Excel中使用公式时,它不会给出相同的结果。我们一直在寻找没有成功的解决方案,请您看看代码吗?

故事:检查“ id”是否在“ sheetName”的A列中。如果是,则检查给定的“ priceDate”是否在期限内的X-Y列。如果还有更多带有“ id”的列,请检查所有行。如果发现在该时间段内也存在某些内容,则退回第V列中的条目。如果没有,则给出0。

非常感谢!

Option Explicit

Function GetDiscount(sheetName As String, id As String, priceDate As Date)

On Error GoTo onError

Const DISCOUNT_COL = 22
Const FROM_DATE_COL = 24
Const TO_DATE_COL = 25

Dim fromDate, toDate As Date
Dim acol, found As Range
Dim firstAddress As String

With Worksheets(sheetName)
    Set acol = .Range("A2:A10000")
    Set found = acol.Find(what:=id, LookIn:=xlValues, LookAt:=xlWhole)

    If Not found Is Nothing Then
        firstAddress = found.Address

        Do
            fromDate = DateValue(.Cells(found.Row, FROM_DATE_COL).Value)
            toDate = DateValue(.Cells(found.Row, TO_DATE_COL).Value)

            If priceDate >= fromDate And priceDate <= toDate Then
                GetDiscount = .Cells(found.Row, DISCOUNT_COL).Value
                Exit Function
            End If

            Set found = acol.FindNext(found)
            If found Is Nothing Then
                GetDiscount = 0
                Exit Function
            End If
        Loop While found.Address <> firstAddress
    End If
End With

GetDiscount = 0
Exit Function

onError:
    MsgBox err.Description
End Function

0 个答案:

没有答案