访问VBA代码不将变量设置为查询值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问VBA代码不将变量设置为查询值相关的知识,希望对你有一定的参考价值。
我是VBA的新手,已经和它一起工作了2个月,但我现在被困住了。我有一个访问代码,用于从包含小时记录的表中计算项目的总小时数。我的代码成功计算了3个类别的小时数,但不计算最后两个类别我从按项目总计小时的查询中提取值并将其保存到变量,然后使用正确的值更新我的项目记录。
更新:对于第4次检查我使用select来查看它是否会更好地工作而不是使用IF语句,它最初是一个if语句。
任何帮助是极大的赞赏。
我的代码如下:
Dim First As Integer
Dim Second As Integer
Dim Third As Integer
Dim Fourth As Integer
Dim Fifth As Integer
Set db = CurrentDb
Set rs = db.OpenRecordset("qryHermosaPCHoursSum1st", dbOpenDynaset, dbSeeChanges)
rs.FindNext "PlanCheck Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
If rs.NoMatch Then
First = 0
Else
First = (rs![SumOfHours])
End If
Set rs = db.OpenRecordset("qryHermosaPCHoursSum2nd", dbOpenDynaset, dbSeeChanges)
rs.FindNext "PlanCheck Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
If rs.NoMatch Then
Second = 0
Else
Second = (rs![SumOfHours])
End If
Set rs = db.OpenRecordset("qryHermosaPCHoursSum3rd", dbOpenDynaset, dbSeeChanges)
rs.FindNext "PlanCheck Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
If rs.NoMatch Then
Third = 0
Else
Third = (rs![SumOfHours])
End If
到这里它工作正常。
Set rs = db.OpenRecordset("qryHermosaPCHoursSum4th", dbOpenDynaset, dbSeeChanges)
rs.FindNext "PlanCheck Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
Select Case True
Case rs.NoMatch
Fourth = 0
Case Else
Fourth = (rs![SumOfHours])
End Select
当我逐行运行代码时,它似乎正确地获取了rs![SumOfHours]的值,但未能将值传递给Fourth和Fifth。我有一个测试记录有15个匹配的小时,查询正确总和但代码将其保留为零。
Set rs = db.OpenRecordset("qryHermosaPCHoursSum5th", dbOpenDynaset, dbSeeChanges)
rs.FindNext "PlanCheck Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
If rs.NoMatch Then
Fifth = 0
Else
Fifth = (rs![SumOfHours])
End If
Set rs = db.OpenRecordset("tblHermosaBeachPC", dbOpenDynaset, dbSeeChanges)
rs.FindNext "ID Like " _
& Chr(34) & "*" & Me.PlanCheck & "*" & Chr(34)
rs.Edit
rs![1stSetHours] = First
rs![2ndSetHours] = Second
rs![3rdSetHours] = Third
rs![4thSetHours] = Fourth
rs![5thSetHours] = Fifth
rs.Update
答案
保存汇总数据通常是不必要的和糟糕的设计。需要时计算汇总数据。
单个查询应该能够计算所有5个聚合值,然后单个记录集可以检索字段。为什么使用通配符而不是=?
Set rs = db.OpenRecordset("SELECT * FROM qryHermosaPCHoursSum WHERE PlanCheck = '" & Me.PlanCheck & "'", dbOpenDynaset, dbSeeChanges)
If Not rs.EOF Then
Set rsDest = db.OpenRecordset("SELECT * FROM tblHermosaBeachPC WHERE PlanCheck = '" & Me.PlanCheck & "'", dbOpenDynaset, dbSeeChanges)
rsDest.Edit
rsDest![1stSetHours] = rs!First
rsDest![2ndSetHours] = rs!Second
rsDest![3rdSetHours] = rs!Third
rsDest![4thSetHours] = rs!Fourth
rsDest![5thSetHours] = rs!Fifth
rsDest.Update
End If
或者代替rsDest记录集对象:
CurrentDb.Execute "UPDATE tblHermosaBeachPC SET 1stSetHours=" & rs!First & _
", 2ndSetHours=" & rs!Second & ", 3rdSetHours=" & rs!Third & _
", 4thSetHours=" & rs!Fourth & ", 5thSetHours=" & rs!Fifth & _
" WHERE PlanCheck = '" & Me.PlanCheck & "'"
以上是关于访问VBA代码不将变量设置为查询值的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Access VBA 将具有默认值的未绑定文本框的值设置为空字符串