我已经研究了所有的STACKOVERFLOW问题,但无法使其正常工作。我有一个简单的表:



和形式:



我想从表T:ActityRoster中提取字段,并从表单中提取“活动日期”,然后将它们“添加”到表T:ActivityHistory中。



一个STACKOVERFLOW专家帮助了我一些代码,但它甚至没有设置第一个记录集:rsIn

Dim ActID As Integer, actDate As Date, val1 As Long, val2 As Long, val3 As Boolean, val4 As Currency

Dim db As Database, rsIn As Recordset, rsOut As Recordset

Dim strSQL As String

Set db = CurrentDb

ActID = Me.cboActivityName.Column(0)

strSQL = "SELECT * FROM T:ActivityRoster WHERE [ActivityID] = ActID"

Debug.Print strSQL

Set rsIn = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)

rsIn.MoveLast

Set rsOut = db.OpenRecordset("T:AttendanceHistory", dbOpenDynaset, dbEditAdd)

rsOut.MoveLast

actDate = Me.ActivityDate.Value  ' retrive the date from the form

With rsIn
    .MoveFirst
    Do
    val1 = !ActivityID
    val2 = !MemberID
    val3 = !Attended
    val4 = !AmtSpent

           With rsOut
               .AddNew
               !ActivityDate = actDate
               !ActivityID = val1
               !MemberID = val2
               !Attended = val3
               !AmtSpent = val4
               .Update
           End With

    .MoveNext
    Loop Until .EOF
    .Close

End With

rsOut.Close
Set rsIn = Nothing
Set rsOut = Nothing
Set db = Nothing

End Sub


我已经验证所有字段名称都是正确的并且是一致的数据类型。当我将查询放回Access时,它给出了预期的结果。

最佳答案

SELECT语句包含VBA变量的名称(ActID):



strSQL = "SELECT * FROM T:ActivityRoster WHERE [ActivityID] = ActID"


不幸的是,数据库引擎对该变量一无所知。因此,当看到ActID时,它假定是您尚未为其提供值的参数的名称。

生成SELECT语句时,请包含变量的值而不是其名称。使用以下两个示例之一:如果[ActivityID]是text数据类型,则第一个;如果是数字数据类型,则返回第二个:

strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = '" & ActID & "'"
strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = " & ActID


我将表名称括在方括号中,因为该名称包含标点符号。但是,如果可能,我将重命名表。对于T:AttendanceHistory也是如此。选择不包含标点和空格且与VBA或SQL关键字不匹配的对象名称。

或者,您可以使用参数查询并为参数值提供ActID:

strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = [which_ActivityID]"
Dim qdf As DAO.QueryDef
Set qdf = db.CreateQueryDef(vbNullString, strSQL)
qdf.Parameters("which_ActivityID").Value = ActID
Set rsIn = qdf.OpenRecordset(dbOpenSnapshot)

关于ms-access - 为什么运行时错误“3061”。参数太少。预期1? Access 2010,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29777371/

10-16 07:37