access vba编程中新建查询时,如果新建的查询名在数据库中已经存在,程序将出错。因而,在新建查询前应查看查询名是否存在。
Dim dbsCurrent As Database
Dim qryTest As QueryDef
Set dbsCurrent = CurrentDb
'---------------------查看查询.Query_temp是否存在-------------------
Dim I As Integer
Dim tblA As Boolean
dbsCurrent.QueryDefs.Refresh
For I = 0 To dbsCurrent.QueryDefs.Count - 1
If "Query_temp" = dbsCurrent.QueryDefs(I).Name Then
'如果查询名:Query_temp存在
tblA = True
Exit For
End If
Next I
'--------------------------------------------------------------------
If tblA Then '如果查询名:Query_temp存在,引用本查询
Set qryTest = dbsCurrent.QueryDefs("Query_temp")
Else '如果查询名:Query_temp不存在,建立本查询
Set qryTest = dbsCurrent.CreateQueryDef("Query_temp")
End If
'以下设置本查询的SQL,得到表strQUR_now的一字段Combo27.Value 的不同值组合
'其中strQUR_now是自定义string变量记录表名,Combo27.Value 为表的一字段名
qryTest.SQL = "SELECT distinct " & Combo27.Value & " FROM " & strQUR_now
'将得到的不同值的组合放到Combo29的列表中
Combo29.RowSource = qryTest.SQL
DoCmd.DeleteObject acQuery, "Query_temp" '注意对象在打开时不能被删除!