【发布时间】:2015-06-16 10:12:20
【问题描述】:
我试图将 VBA excel 中的代码转换为 access。我的数据是一列价格,我想计算收益。 这是excel中的原始VBA代码:
DerCol = Cells(T.Row, Columns.Count).End(xlToLeft).Column
Cells(T.Row, DerCol + 1) = "Returns"
For i = T.Row + 2 To T.End(xlDown).Row
Cells(i, DerCol + 1) = Application.WorksheetFunction.Ln(Cells(i, T.Column)) - Application.WorksheetFunction.Ln(Cells(i - 1, T.Column))
Next i
要了解我在 excel 中的输出,请单击 here。 在 Access 中,我在价格列旁边创建了一个新列,我想像在 excel 中一样填写:
Sub vardaily()
Dim db As Database, T As Object, DerCol As Integer, y As TableDef
Dim rs As DAO.Recordset, i As Integer, strsql As String
'idea = SELECT prices FROM dailypricing, then creates newtable "VAR", copy and prices, compute historical and parametric VAR '
'create a new table var_daily'
Set db = CurrentDb()
'insert the pricing date and the prices from dbo_daily'
db.Execute "CREATE TABLE VAR_daily" _
& "(PricingDate CHAR, Price Number);"
'where clause to select the same traded product only'
db.Execute " INSERT INTO VAR_daily " _
& "SELECT PricingDate, Price " _
& "FROM dbo_PricingDaily " _
& "WHERE IndexId = 1;"
db.Execute " ALTER TABLE VAR_daily " _
& "ADD COLUMN Returns Number;"
'sql request to store prices'
strsql = "SELECT First(Price) as FirstPrice, Last(Price) as EndPrice FROM VAR_daily;"
'dao.recordset of the store prices'
Set rs = db.OpenRecordset(strsql, dbOpenDynaset)
'loop to change the prices'
For i = 2 To i = rs.RecordCount
rs.Edit
rs!Price(i) = Log(rs!Price(i)) - Log(rs!Price(i - 1))
rs.Update
Next i
db.Execute "INSERT INTO VAR_daily " _
& "(Returns) VALUES " _
& "(" & rs![Price] & ");"
End Sub
我有下表你可以看到here 我无法管理循环。最后,我的收藏中没有任何物品。 我查看了其他循环示例,例如 here,但我没有找到如何使用最后一个结果进行迭代。
对不起,我真的是 Access 和 SQL 的初学者。我从本周开始,所以如果我的问题非常基本,我深表歉意。
编辑:我添加了图片,并将 Firsttransaction 和 Lasttransaction 替换为“FirstPrice”和“EndPrice”。
EDIT2:感谢我的新特权,我可以将a sample 分享给有兴趣的人。
【问题讨论】:
-
您能否编辑您的帖子以显示一些示例数据和您希望看到的结果?为什么需要存储这个值?
-
我没有足够的声誉来发布图片但是here,您可以在“fermer”列下看到一个索引,以及在“Returns”列下计算的每个时期的收益
-
你可以发一个链接到 imgur 什么的?
-
我做了,点击上一篇文章中的“这里”。
-
我非常感谢您在表格中添加数据的屏幕截图方面所做的努力,但是.. 为什么需要一个新列?为什么这不能在查询中实现?您需要的是修改后的运行总和列。
标签: vba for-loop ms-access iteration recordset