Dlookup VBA代码有2个标准

时间:2013-03-14 19:03:37

标签: forms vba ms-access auto-populate filtered-lookup

我有一个MS Access表单,其中包含project_ID字段组合框和其他几个字段。用户选择project_ID字段后,表单上的大多数后续字段将自动填充。我试图在窗体上添加一个字段,不仅显示基于project_ID的信息,还显示Trans_ID。问题是我希望Trans_ID成为表单上的文本框,用户只需键入Trans_ID,然后在另一个文本框中显示Error_DTL_1字段。这是我到目前为止生成的VBA代码:

Private Sub cboProjectID_Change()

Dim VarComboKey As Integer 
Dim VarObjective As Variant 
Dim VarStartDate As Variant 
Dim VarEndDate As Variant 
Dim VarRiskCategory As Variant 
Dim VarTarDatSet As Variant

Dim VarErrorCount As Variant 
Dim VarErrorCode As Variant

Dim VarErrorDTL As Variant

VarComboKey = Me.cboProjectID.Value

VarObjective = DLookup("[Objective]", "[Project_HDR_T]", "[Project_ID]= " & VarComboKey) 
Me.txtObjective = VarObjective

VarStartDate = DLookup("[Start_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey) 
Me.txtStartDate = VarStartDate

VarEndDate = DLookup("[End_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey) 
Me.txtEndDate = VarEndDate

VarRiskCategory = DLookup("[Risk_Category]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey) 
Me.txtRiskCategory = VarRiskCategory

VartxtTarDatSet = DLookup("[Targeted_Dataset]", "[Project_Targeted_Dataset]", "[Project_ID] = " & VarComboKey)
Me.txtTarDatSet = VartxtTarDatSet

VarErrorCount = DLookup("[Count_Error_Codes]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey)
Me.txtErrorCount = VarErrorCount

VarErrorCode = DLookup("[ErrorCode]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey) 
Me.txtErrorCode = VarErrorCode

VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey And "[Trans_ID] = forms![Quality Risk Assessment]!me.stTransID") 
Me.txtErrorDTL = VarErrorDTL

End Sub  

“End Sub”之前的两行是我试图攻击此代码。但每次我在窗体上的Project_ID组合框中进行选择时,都会出现错误“运行时错误13,类型不匹配”。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

在线......

VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey And "[Trans_ID] = forms![Quality Risk Assessment]!me.stTransID") 

...“And”在引号之外,第二个子句似乎混合了Forms!me.引用方式。尝试...

VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey & " And [Trans_ID] = forms![Quality Risk Assessment]!stTransID.Value") 

......看看它是否效果更好。或者,您可以尝试......

VarErrorDTL = DLookup("[Error_DTL_1]", "[Project_DTA_REV_T]", "[project_ID] = " & VarComboKey & " And [Trans_ID] = " & me.stTransID.Value) 

答案 1 :(得分:3)

记录集:

Dim rs As DAO.Recordset

sSQL = "SELECT p.Objective, p.Start_Date, p.End_Date FROM Project_HDR_T p " _
     & "WHERE p.Project_ID = " & VarComboKey
Set rs = CurrentDb.OpenRecordset(sSQL)

If rs.EOF Then
    MsgBox "oops"
Else
    VarObjective = rs!Objective
    VarStartDate = rs!Start_Date
    VarEndDate = rs!End_Date
End If

鉴于所有表都包含Project_ID,应该可以创建包含所有表的查询,此外,查询可以保存并使用代码中的参数进行引用。

另见:
What is a Recordset in VBA? ... what purpose does it serve?
Recordset Object