2013-07-12 263 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

相關問題