VBA检查2个字段中的不同值是否匹配

时间:2015-06-11 13:41:35

标签: sql database vb.net vba ms-access

我对VBA很新,但有一些编码经验,所以我慢慢开始学习。我的访问数据库中有两个表,每个表都有一个相同的字段。一个表是可能值的明显列表(" TOSITEXREF"),它们可以显示在另一个表的相同字段中(" Trans_Earned")。我试图创建的这个函数将在宏中运行,以确定通过查询附加的数据是否在ToLocn字段中有一个不在可能值列表中的实例。这是我到目前为止所做的,但是不起作用:

Function TESTING()

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("TransEarned")

Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset("TOSITEXREF")

Dim cond1A As Boolean

cond1A = (rs.Fields("ToLocn") = rs2.Fields("ToLoc"))

If cond1A Then
    DoCmd.OpenQuery "Earns", acViewNormal, acEdit
Else
    DoCmd.CancelEvent
    MsgBox "Unknown ToLocation, Please Update TOSITEXREF File to acccount for new location", vbOKOnly, "NEW LOCATION"
End If

Set rs = Nothing
Set rs2 = Nothing

End Function

1 个答案:

答案 0 :(得分:1)

最终的VBA示例将在table1的Loc字段中返回一个值,该值未显示在Table2的Loc字段中:

Function Validate()

Dim sql As String
Dim rs As DAO.Recordset

sql = "SELECT Table1.Loc FROM Table1 LEFT JOIN Table2 ON Table1.Loc =  Table2.Loc WHERE (((Table2.Loc) Is Null))"
Set rs = CurrentDb.OpenRecordset(sql)

If (rs.RecordCount = 0) Then
     MsgBox "WORKS", vbkokonly, "WORKS"
Else
     MsgBox "DOES NOT WORK", vbkokonly, "DOES NOT WORK"

Set rs = Nothing

End If
End Function