2015-04-18 47 views
0

在查询中,我有一个包含太多iif的SQL iif语句,因此我无法添加任何更多的iif,这是一个问题。将复杂的SQL iif语句转换为VBA函数

为了解决这个问题,我有想法编写一个VBA函数,但我面临困难。这里是我的,用一个简单的例子,我们在一个字段中有一个数字。如果数量为< 0,功能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 

但是,这并不工作,因为它检索每条线的最后记录,而不是正确的线。

+0

你可以发布这个SQL打算替换吗? – Comintern

+0

您可以使用开关命令,而不是IIF,这更容易理解。在sql qury中的VBA函数可能会降低您的性能。 –

回答

3

您的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