如何解决在MS Access中,是否可以在查询中添加可更新的空白字段,以在VBA中以编程方式计算其值?
在MS Access中,为了防止嵌套查询,因为它真的变慢了,我试图使用循环在VBA中以编程方式计算查询的所有计算字段。通常,这种想法是完全停止使用查询中的计算字段,而从后端执行所有计算。
我在以连续形式显示文本框中的值时遇到问题。我试图在VBA中使用一个空字段创建查询,然后使用计算出的值更新该字段,因此我可以将文本框的ControlSource设置为该字段,以使其正确显示。问题在于,由于空字段是计算字段,因此我无法更新其值。还有什么其他方法可以将字段添加到查询中,直到我可以计算其值之前,该字段仍为空且可更新?
另一种解决方案是创建一个时态表而不是查询并更新值,但是我真的不希望每次用户需要对计算字段(特别是嵌套字段)进行查询时都不要创建时态表。 有没有办法做到这一点?
这是我尝试过的:
Private Sub Form_Load()
Dim SQLQ As string
Dim rs As DAO.Recordset
Dim dbs As DAO.Database
Dim qrydef As DAO.QueryDef
Dim i As Integer
'calcField1 is not a member of Items,and it's intended to be updated later on
SQLQ = "SELECT Items.Price,calcField1 FROM Items;"
Set dbs = CurrentDb()
Set qrydef = dbs.CreateQueryDef("testqry",SQLQ)
'Field is prompted for a value when the query is called and has no source
qrydef!calcField1 = vbNullString
Set rs = qrydef.OpenRecordset()
i = 0
Do Until rs.EOF
rs.Edit
rs!calcField1 = rs!Price *2 'Error here because calcField1 is a Calculated Field
rs.Update
i = i + 1
rs.MoveNext
Loop
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.Recordset = rs
Me.Refresh
End Sub
解决方法
我认为最好创建另一个表,在该表中可以插入对原始表的引用的新计算记录,以便将它们链接起来。
例如:
表1: item_id,item_desc,价格
表2: item_id,计算值
然后,可以根据您的计算过程的目的来插入或修改计算值。
,您可以将计算出的字段添加到查询中并将其用作记录源吗?
Private Sub Form_Load()
Dim strSQL As string
'calcField1 is calculated
strSQL = "SELECT Items.Price,(Items.Price * 2) AS calcField1 FROM Items;"
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.RecordSource = SQLQ
Me.Refresh
End Sub
或者如果逻辑更复杂,您可以将其放入函数中
'in the form
Private Sub Form_Load()
Dim strSQL As string
'calcField1 is computed by a function
strSQL = "SELECT Items.Price,MyFunction(Items.Price) AS calcField1 FROM Items;"
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.RecordSource = strSQL
Me.Refresh
End Sub
'in a module
Public Function MyFunction(dbl As Double) As Double
MyFunction = dbl * 2
End Function
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。