Looping Through Dates in strSQL in Access VBA

2019-09-07 15:28发布

I have this code in Access:

Sub SampleReadCurve()

Dim rs As Recordset
Dim iRow As Long, iField As Long
Dim strSQL As String
Dim CurveID As Long
Dim MarkRunID As Long
Dim MaxOfMarkAsofDate As Date



CurveID = 15

MaxOfMarkAsofDate = #7/22/2015#


strSQL = "SELECT * FROM VolatilityOutput WHERE CurveID=" & CurveID & " AND MaxOfMarkAsofDate=#" & MaxOfMarkAsofDate & "# ORDER BY MaxOfMarkasOfDate, MaturityDate"


Debug.Print strSQL

Set rs = CurrentDb.OpenRecordset(strSQL, Type:=dbOpenDynaset, Options:=dbSeeChanges)

If rs.RecordCount <> 0 Then
    rs.MoveFirst
    Debug.Print vbCrLf
    Debug.Print "First", rs.Fields("ZeroCurveID"), rs.Fields("MaturityDate"), rs.Fields("ZeroRate"), rs.Fields("DiscountFactor")
    rs.MoveLast
    Debug.Print "Last", rs.Fields("ZeroCurveID"), rs.Fields("MaturityDate"), rs.Fields("ZeroRate"), rs.Fields("DiscountFactor")
    Debug.Print "There are " & rs.RecordCount & " records and " & rs.Fields.Count & " fields."

    Dim BucketTermAmt As Long
    Dim BucketTermUnit As String
    Dim BucketDate As Date
    Dim MarkAsOfDate As Date
    Dim InterpRate As Double
    Dim I As Integer

    BucketTermAmt = 3
    BucketTermUnit = "m"
    BucketDate = DateAdd(BucketTermUnit, BucketTermAmt, MaxOfMarkAsofDate)
    InterpRate = CurveInterpolateRecordset(rs, BucketDate)
    Debug.Print BucketDate, InterpRate




End If
End Sub

The table VolatilityOutput has a list of dates with an associated value. This code interpolates a value for a given MaxofMarkAsofDate using the closest values found in the table.

Right now, I have MaxofMarkAsofDate selected from the table as part of an strSQL statement. The code returns the correct value for #7/22/2015#.

However, I need to get the values for the 76 dates prior to #7/22/2015#. I can accomplish this by manually entering #7/21/2015#, #7/20/2015# etc for each date. I would like to do this a faster way if possible. I want to use a loop however I don't know how to combine loops with strSQL statements in Access.

1条回答
冷血范
2楼-- · 2019-09-07 16:11
CurveID = 15

Dim i As Integer    
For i = 0 to 76
    MaxOfMarkAsofDate = #7/22/2015# - i

    'Your inner code here '
Next i

End Sub
查看更多
登录 后发表回答