在Access VBA中移动Recordset

时间:2015-10-26 14:21:09

标签: vba ms-access access-vba recordset

我有一个使用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中循环遍历电子表格?

2 个答案:

答案 0 :(得分:1)

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

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

您也可以使用表格查询填充它。

转到记录集的开头

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

循环记录集

Do While rs.EOF = False

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

rs.MoveNext
Loop

答案 1 :(得分:1)

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

Recordset.GetRows Method

然后,新代码将几乎是您已验证代码的复制粘贴,基本上从以下开始:

vZeros = rsCurve.GetRows(rsCurve.RecordCount)

作为旁注,你不需要CDate:

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