2015-04-18 50 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