2014-02-10 73 views
0

我是VBA的新手,需要獲取幫助才能獲得工作指令。我需要查看2個值,並在按下按鈕時創建新記錄。我對dlookup有問題。基本的VBA代碼(dlookup)

Private Sub Add_Record_Click() 
Dim db As Database 
Dim r As Recordset 
Dim x As Integer 

Set db = CurrentDb 
Set r = db.OpenRecordset("Copy Of Employee Work Statistics") 

Y = r.Fields("School") 
z = r.Fields("School Id") 

Y = DLookup(Table![Routes].School, Table![Routes], "Route" = Table![Routes].[Route Name]) 
z = DLookup("school ID", "Customer Database", "school" = Y) 

r.Update 

DoCmd.GoToRecord , , acNewRec 

End Sub 

回答

0

DLookup("school ID", "Customer Database", "school" = Y)

你的語法是不對的,你應該包括所有的字符串中的標準(第三個參數),如下所示:

DLookup("[school ID]", "[Customer Database]", "[school] = '" & Y & "'")

其中&用於字符串連接,Y是你以前聲明的變量。爲了避免由於保留字引起的任何衝突或由於名稱中的空格造成的任何有趣錯誤,我還鼓勵您在引用列名或表名時使用方括號([])。

至於更新部分,Y和z只是變量。我猜你的意圖是,直接更新你的記錄集。因此:

r.Fields("School") = DLookup("[" & Table![Routes].School & "]", _ 
"[" & Table![Routes] & "]", "[Route] = '" & Table![Routes].[Route Name] & "'") 

r.Fields("School Id") = DLookup("[school ID]", "[Customer Database]", _ 
"[school] = '" & Y & "'") 

r.Update