我刚刚开始使用 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')
编辑:添加了缺少的引号。