【问题标题】:Transform a complex SQL iif statement into a VBA function将复杂的 SQL iif 语句转换为 VBA 函数
【发布时间】:2015-04-21 18:26:39
【问题描述】:

在查询中,我有一个包含太多 iif 的 SQL iif 语句,因此我无法添加更多 iif,这是一个问题。

为了解决这个问题,我有编写 VBA 函数的想法,但我遇到了困难。这是我所拥有的,有一个简单的例子,我们在一个字段中有一个数字。如果数字Retrive()应该检索字段TheDate的值,如果>0,函数应该检索字段TheOtherDate的值:

Public Function Retrive(NumberToCheck As Integer) As Date
Dim db As Database
Dim r As Recordset
Dim rsCount As Integer
Dim TheDate As Field, TheOtherDate As Field
Dim i As Integer

Set db = CurrentDb()
Set r = db.OpenRecordset("Table")
Set TheDate = r.Fields("TheDate")
Set TheOtherDate = r.Fields("TheOtherDate")

rsCount = r.RecordCount

r.MoveFirst

For i = 1 To rsCount
    If NumberToCheck < 0 Then
        Retrive = TheDate.Value
    End If
    If NumberToCheck > 0 Then
        Retrive = TheOtherDate.Value
    End If
    r.MoveNext
Next i

End Function

但这不起作用,因为它检索每一行的最后一条记录,而不是正确的行。

【问题讨论】:

  • 你能发布这个打算替换的 SQL 吗?
  • 您可以使用 switch 命令代替 IIF,这更容易理解。SQL 查询中的 VBA 函数可能会降低您的性能。

标签: ms-access vba


【解决方案1】:

您的For 循环会一直运行,直到您到达最后一条记录然后退出。当你到达正确的记录时,你必须跳出循环(你决定如何确定这一点)。

Option Explicit

Public Function Retrive(NumberToCheck As Integer) As Date
    Dim db As Database
    Dim r As Recordset
    Dim rsCount As Integer
    Dim TheDate As Field, TheOtherDate As Field
    Dim TheRightDate As Date
    Dim i As Integer

    Set db = CurrentDb()
    Set r = db.OpenRecordset("Table")
    Set TheDate = r.Fields("TheDate")
    Set TheOtherDate = r.Fields("TheOtherDate")

    rsCount = r.RecordCount

    r.MoveFirst

    TheRightDate = DateValue("1/15/2015")

    For i = 1 To rsCount
        If NumberToCheck < 0 Then
            Retrive = TheDate.Value
            '--- check here to see if you have the correct value
            '    and if so, the exit the loop
            If Retrive = TheRightDate Then
                Exit For
            End If
        End If
        If NumberToCheck > 0 Then
            Retrive = TheOtherDate.Value
            '--- check here to see if you have the correct value
            '    and if so, the exit the loop
            If Retrive = TheRightDate Then
                Exit For
            End If
        End If
        r.MoveNext
    Next i
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多