1

我刚刚开始使用 Access 进行一些编码并尝试创建一个将行添加到表中的函数,但这不起作用。

我创建了一个简单的表(Table1),其中包含两列“FirstName”和“LastName”以及一个触发以下代码的按钮:

Private Sub Command0_Click()
    AppendRow "Table1", "John", "Doe"
End Sub

AppendRow 在哪里:

Function AppendRow(toTableName As String, firstName As String, lastName As String) As Boolean
   ' Returns True on success, false otherwise
   ' USAGE: AppendRow "toTableName", "firstName", "lastName"

   On Error GoTo errhandler
   Dim strSql As String

   'Create the SQL string
   strSql = "INSERT INTO " & toTableName & " (FirstName, LastName) " & _
        "VALUES ('" & firstName & "', '" & lastName & "');"


   'Print the SQL so we can paste into the query build if there are errors
   Debug.Print strSql
   MsgBox strSql

   'Run the SQL Query
   CurrentDb.Execute strSql

   'If no errors return true
   AppendRow = True

ExitHere:
   Exit Function

errhandler:
   'There is an error return false
   AppendRow = False
   With Err
      MsgBox "Error " & .Number & vbCrLf & .Description, vbOKOnly Or vbCritical, "AppendTable"
   End With
   Resume ExitHere
End Function

SQL 字符串如下所示

INSERT INTO Table1 (FirstName, LastName) VALUES ('John', 'Doe')

编辑:添加了缺少的引号。

4

2 回答 2

2

您报告说您现在引用了您尝试插入的文本值,但是您没有插入该行并且显然没有错误消息。我不明白为什么会这样,并提供这个简单的程序只是为了看看你是否可以得到一些工作。

Public Sub AppendRow(ByVal toTableName As String, _
        ByVal pFirstName As String, _
        ByVal pLastName As String)
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    '* ensure SetWarnings is not off *'
    DoCmd.SetWarnings True
    Set db = CurrentDb
    Set rs = db.OpenRecordset(toTableName, dbOpenTable, dbAppendOnly)
    With rs
        .AddNew
        !firstName = pFirstName
        !lastName = pLastName
        .Update
        .Close
    End With
    Set rs = Nothing
    Set db = Nothing
End Sub

我没有包括错误处理,因为这仅用于测试。我将其设为子例程而不是函数,因为我注意到您没有在调用该函数的代码中使用该函数的返回值。

如果这对您不起作用,请告诉我们您收到的错误消息以及该过程中的哪一行触发了错误。

于 2012-09-17T17:30:24.037 回答
1

在我从 OpenRecordSet 函数调用中删除 dbAppendOnly 选项之前,HansUp 的代码对我不起作用。MS 帮助文档暗示它仅对 Dynaset RecordSets 有效,对 TableSet Recordsets 无效。将其更改为“Set rs = db.OpenRecordset(toTableName, dbOpenTable)”并且它起作用了。

但他的代码非常有帮助,我非常感激。我一直在四处走动,也无法让我的 .Execute "INSERT"...-type 代码工作。我不知道这是怎么回事。它曾经奏效过,我做了一个小改动……也许我的血压因恶化而达到顶峰与此有关。

顺便说一句,@ymail.com 是一个有效的电子邮件域,尽管您的自动地址检查器说了什么。

于 2013-11-06T13:25:31.060 回答