在 Access 中浏览记录集 VBA

Moving through the Recordset in Access VBA

我有一个使用 Excel VBA 的简单函数来计算波动率。它以一列数字(零)和两个日期作为输入。代码是:

Function EWMA(Zeros As Range, Lambda As Double, MarkDate As Date, MaturityDate As Date) As Double

    Dim vZeros() As Variant
    Dim Price1 As Double, Price2 As Double
    Dim SumWtdRtn As Double
    Dim I As Long
    Dim m As Double

    Dim LogRtn As Double, RtnSQ As Double, WT As Double, WtdRtn As Double

vZeros = Zeros

m = Month(MaturityDate) - Month(MarkDate)

For I = 2 To UBound(vZeros, 1)

    Price1 = Exp(-vZeros(I - 1, 1) * (m / 12))

    Price2 = Exp(-vZeros(I, 1) * (m / 12))

    LogRtn = Log(Price1 / Price2)

    RtnSQ = LogRtn ^ 2

    WT = (1 - Lambda) * Lambda ^ (I - 2)

    WtdRtn = WT * RtnSQ

    SumWtdRtn = SumWtdRtn + WtdRtn

Next I

EWMA = SumWtdRtn ^ (1 / 2)

End Function

使该函数起作用的主要特点是For循环。我想使用记录集对象在 Access VBA 中重新创建它。记录集与 Excel 电子表格具有相同的字段。不过,我不确定如何转换代码。这是我目前所拥有的:

Function EWMA(rsCurve As Recordset, InterpRate As Double, Lambda As Double) As Double

    Dim vZeros() As Variant
    Dim Price1 As Double, Price2 As Double
    Dim SumWtdRtn As Double
    Dim I As Long
    Dim mat As Date
    Dim mark As Date

    Dim LogRtn As Double, RtnSQ As Double, WT As Double, WtdRtn As Double


    CurveInterpolateRecordset = Rnd()

    If rsCurve.RecordCount <> 0 Then

    vZeros = CVar(rsCurve.Fields("CurveInterpolateRecordset"))

    mat = CDate(rsCurve.Fields("MaturityDate"))
    mark = CDate(rsCurve.Fields("MarkDate"))

    m = Month(mat) - Month(mark)

For I = 2 To UBound(vZeros, 1)

    Price1 = Exp(-vZeros(I - 1, 1) * (m / 12))

    Price2 = Exp(-vZeros(I, 1) * (m / 12))

    LogRtn = Log(Price1 / Price2)

    RtnSQ = LogRtn ^ 2

    WT = (1 - Lambda) * Lambda ^ (I - 2)

    WtdRtn = WT * RtnSQ

    SumWtdRtn = SumWtdRtn + WtdRtn

Next I

EWMA = SumWtdRtn ^ (1 / 2)

End If

        Debug.Print EWMA

End Function

该函数在 Access 的早期子例程中调用。为了在 Access 中移动记录集,我缺少什么,类似于在 Excel VBA 中循环电子表格?

以下是有关使用记录集的一些基础知识。

Dim rs As New ADODB.Recordset

'Add fields to your recordset for storing data.
With rs
    .Fields.Append "Row", adInteger
    .Fields.Append "ColumnName2", adChar, 30
    .Fields.Append "ColumnName3", adInteger
    .Open
End With

手动添加记录

rs.AddNew
rs.Fields("Row").Value = 1
rs.Fields("ColumnName2").Value = "Put some value in"   
rs.Update

rs.AddNew
rs.Fields("Row").Value = 2
rs.Fields("ColumnName2").Value = "Put another value in"   
rs.Update

您还可以使用 table.

的查询来填充它

移动到记录集的开头

If rs.EOF = False Then
    rs.MoveFirst
End If

遍历记录集

Do While rs.EOF = False

        msgbox(rs.Fields("ColumnName2").Value)

rs.MoveNext
Loop

最简单的方法是使用 GetRows 从记录集中提取数组:

Recordset.GetRows Method

那么新代码几乎就是您经过验证的代码的复制粘贴,基本上是这样开始的:

vZeros = rsCurve.GetRows(rsCurve.RecordCount)

附带说明一下,您在这里不需要 CDate:

mat = rsCurve.Fields("MaturityDate").Value