访问VBA - 比较表中的记录

时间:2016-03-24 07:26:40

标签: access-vba ms-access-2010

我有两个表,我想比较记录 - 基于字段值。这是我试过的:

 Dim RCount As Long

    Dim Rst As Recordset
    Dim Rst1 As Recordset
    Dim f As Field

    'Current Record set
    Set Rst = CurrentDb.OpenRecordset("Table1")
    Set Rst1 = CurrentDb.OpenRecordset("Table2")

    With Rst

    For Each f In Rst1.Fields

    RCount = DCount("FieldFromTable1", "Table1", "[FieldFromTable1]='" & Me.[FieldFromTable2].Value & "'")

    If RCount > 0 Then
           Me.Checkbox1.Value = True
    End If

     Next f

    End With

    Rst.Close
    Rst1.Close

这是我更新的问题,就像我想要完成的那样。但是这段代码仍然只能通过我的Table2表格中当前选择的记录循环。

2 个答案:

答案 0 :(得分:0)

继续发表评论。您可以使用记录计数来查看是否存在存在且匹配的记录。您可以使用以下查询来查看是否存在记录:

dim rst as recordset
dim varSQL as string

varSQL = "SELECT [fieldfromtable1] FROM Table1 WHERE [fieldfromtable1] ='" & [fieldfromtable2].value & "'"

Set Rst = CurrentDb.OpenRecordset(varSQL)

  If rst.recordcount = 1 then
   MsgBox "Fields have matching values !"
  End If
rst.close

您可以将=1替换为>0

或者,我认为您可以使用dcount()函数,类似于:

dim RCount as long

Rcount = dcount("fieldFromTable1","table1", "[fieldFromTable1]='" & me.[FieldFromTable2].value & "'")

if Rcount > 0 then
       MsgBox "Fields have matching values !"
end if

再次,您可以使用>0=1我不确定哪种情况最适合您的情况。

  

修改

可以执行以下查询来更新复选框,但这不是表单级别

UPDATE table1 INNER JOIN table2 ON table1.[fieldfromtable1] = table2.[fieldfromtable2] SET table1.[checkboxField] = True
WHERE table2.[fieldfromtable2]= table1.[fieldFromtable1]

答案 1 :(得分:0)

我还没有真正考虑只在表中更新记录的选项。 Thsi是它对我有用的东西。当Table1中的记录符合表2中的条件时,我只是试图将Checkbox设置为TRUE。一个简单的UPDATE解决了这个问题:

Dim SQL As String

niz = " UPDATE Table2" & _
      " INNER JOIN Table1" & _
      " ON Table1.FieldFromTable1=Table2.FieldFromTable2" & _
      " SET Table2.Checkbox1=True"
DoCmd.SetWarnings False

DoCmd.RunSQL niz
DoCmd.Requery
DoCmd.SetWarnings True