【发布时间】:2019-11-26 16:28:51
【问题描述】:
我是 VBA 新手,正在尝试获取我正在编写的宏,以检查是否已经存在与要添加的新记录的日期/班次组合相对应的预先存在的记录。为此,我正在尝试使用 DLookup 搜索数据库,并且仅在 DLookup 返回 Null 时才允许新记录,除非它找到日期和班次都与新数据匹配的记录(我' m 使用复合主键使用这两条数据)。唉,正如标题所说,我不断收到运行时错误 424,当我调试它时它会突出显示
lookTest = Access.DLookup("Shift", "trialTable", "[Date of Production]=#" & shiftDate & "#" & "And [Shift]='" & currentShift & "'")
作为问题线。 (“Shift”和“Date of Production”是用作复合键的两列的列标题,“trialTable”是我正在使用的表,“shiftDate”是日期,“currentShift”是字符串)据我所知,我的语法是正确的,所以我不知道此时我哪里出了问题(我敢肯定,这可能是愚蠢而明显的事情)。如果它有帮助,下面是导致该点的其余代码,以防我之前搞砸了一些东西,而计算机直到它到达那条线才意识到它。非常感谢任何帮助,谢谢!
Sub DatabaseUpdate()
' exports data from the active spreadsheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0; " & "Data Source=H:\TestingDatabase.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "trialTable", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records on a table
With rs
.AddNew 'create a new record
'Ask the user which shift the report is for.
Dim currentShift As String
Dim shiftDate As Date
Dim shiftCheck As Boolean
shiftCheck = False
' Request and check if the user has entered in a valid shift. If so, continue. If not, inform them and then repeat the request for the shift identity.
Do While shiftCheck = False
currentShift = UCase(InputBox("Which shift is this entry for? Please input only A, B, or C. (not case-sensitive)"))
If currentShift = "A" Or currentShift = "B" Or currentShift = "C" Then
shiftCheck = True
Else
wrongLetterWarning = MsgBox("Sorry, that is not an accepted response (A, B, or C). Please try again.", vbOKOnly)
End If
Loop
' Request the date the shift occured on. MM/DD/YYYY format is important as the date and shift together form the database's primary key.
shiftDate = InputBox("On which date did this shift occur? Please use MM/DD/YYYY format.")
'Check to make sure that there isn't already a pre-existing record for the date/shift combination.
Dim lookTest As Variant
lookTest = Access.DLookup("Shift", "trialTable", "[Date of Production]=#" & shiftDate & "#" & "And [Shift]='" & currentShift & "'")
【问题讨论】:
-
什么是
Access? -
开启
Option Explicit,看看编译时会发生什么。 -
@GSerg:MS Access @braX:首先它让我将变量 wrongLetterWarning 指定为一个变体,现在它出于某种原因将 Access 标记为一个变量(它不是一个)并说它是未定义的。
-
当然是未定义的。 MS Access 对象模型中没有
Access这样的东西。虽然有Application,但它确实有DLookUp作为它的方法。 -
@Grahammophone 该 VBA 代码是包含在 Excel 项目还是 Access 项目中?
DatabaseUpdate中的代码注释提到了“excel 电子表格”。
标签: vba ms-access runtime-error dlookup