2013-07-12 265 views
2

我的代码工作,除了这一条线如何将rst.FindFirst与rst.NoMatch一起使用?

.FindFirst "[DONOR_CONTACT_ID] = strTemp2" 

我希望我的代码来检查是否有记录,其中特定DONOR_CONTACT_ID存在becaue有具有相同DONOR_CONTACT_ID多个记录。如果该记录不存在,那么我想将该DONOR_CONTACT_ID和RECIPIENT_CONTACT_ID添加到RECIPIENT_1。如果该记录确实存在,我想将RECIPIENT_CONTACT_ID添加到该特定DONOR_CONTACT_ID的RECIPIENT_2。为此,我使用.FindFirst,查看是否有记录,然后使用.NoMatch。如果没有匹配,我想添加一条新记录,但是如果有的话我想检查它是否必须进入RECIPIENT_2。

我得到的错误是“不能识别'strTemp2'作为有效的字段名称或表达式”。我想看看记录是否等于strTemp2,但我认为我的语法是错误的。谢谢你的帮助!!

这里是我的代码:

Option Compare Database 
Option Explicit 

Function UsingTemps() 

Dim dbs As DAO.Database 
Dim rst As DAO.Recordset 
Dim rstOutput As DAO.Recordset 
'Defines DAO objects 
Dim strTemp1 As String 
Dim strTemp2 As String 
Dim strVal As String 
Dim strRecip As String 

DoCmd.SetWarnings False 
DoCmd.OpenQuery ("Q_RECIPIENT_SORT") 
DoCmd.OpenQuery ("Q_DELETE_T_OUTPUT") 
DoCmd.SetWarnings True 
Set dbs = CurrentDb 

Set rst = dbs.OpenRecordset("T_RECIPIENT_SORT", dbOpenDynaset) 
'rst refers to the table T_RECIPIENT_SORT 
Set rstOutput = dbs.OpenRecordset("T_OUTPUT", dbOpenDynaset) 
'rstOutput refers to the table T_OUTPUT 

rst.MoveFirst 
'first record 
strTemp1 = rst!DONOR_CONTACT_ID 
'sets strTemp1 to the first record of the DONOR_CONTACT_ID 
rst.MoveNext 
'moves to the next record 


    Do While Not rst.EOF 
    'Loop while it's not the end of the file 
     strTemp2 = rst!DONOR_CONTACT_ID 
     'strTemp2 = DONOR_CONTACT_ID from T_RECIPIENT_SORT 

    If strTemp1 = strTemp2 Then 
    'Runs if temps have same DONOR_CONTACT ID 
     strRecip = rst!RECIPIENT_CONTACT_ID 
    'Sets strRecip = RECIPIENT_CONTACT_ID FROM T_RECIPIENT_SORT 

     With rstOutput 
     'Uses T_OUTPUT table 
      If .RecordCount > 0 Then 
      'If table has records then you can check 
       .FindFirst "[DONOR_CONTACT_ID] = strTemp2" 
       If .NoMatch Then 
        .AddNew 
        !DONOR_CONTACT_ID = strTemp1 
        !RECIPIENT_1 = strRecip 
        .Update 
       Else 

        If !DONOR_CONTACT_ID = strTemp2 Then 
         If IsNull(!RECIPIENT_2) And Not (IsNull(!RECIPIENT_1)) Then 
          .Edit 
          !RECIPIENT_2 = strRecip 
          .Update 
         End If 
         .AddNew 
         !DONOR_CONTACT_ID = strTemp2 
         !RECIPIENT_1 = strRecip 
         .Update 
        End If 
       End If 

      Else 
       .AddNew 
       !DONOR_CONTACT_ID = strTemp2 
       !RECIPIENT_1 = strRecip 
       .Update 
      End If 

     End With 

    End If 

    strTemp1 = strTemp2 
    rst.MoveNext 

Loop 

Set dbs = Nothing 

End Function 

回答

4

构建变量的值,而不是变量,到你给FindFirst查找的字符串。

假设DONOR_CONTACT_ID是文本数据类型,还包括周围的变量的值的报价...

.FindFirst "[DONOR_CONTACT_ID] = '" & strTemp2 & "'" 

但如果它是数字,你不需要这些报价...

.FindFirst "[DONOR_CONTACT_ID] = " & strTemp2 
+0

连续第二天你帮了我!再次感谢!在我的办公室里没有人知道如何编写代码,所以我非常感谢你在过去两天帮助了我,为我节省了很多时间! – nedstark179

相关问题