VBA在Access中向表中添加新记录

时间:2014-08-28 13:23:42

标签: excel vba append

我有一个(链接)表[Traffic],其中一个字段名为[Log]
我有一个变量IO,可以是“I”或“O”。

此功能的唯一目的是向[Log]列中包含一个字符串的表[Traffic]添加一个新记录/行:每次一个日期戳与“I”或“O”组合表单已加载/卸载。

我尝试在Ms Access 2010中创建一个功能但没有成功(错误:“需要对象”)。

非常感谢任何帮助。

Public Function AppendTxt(IO As String)
Dim sText As String
Dim sTableName As String
Dim col As Integer
Dim lLastRow As Long
Dim iHeader As Integer

sTableName = "Traffic"
sText = Format$(Now, "yyyy\-mm\-dd hhnn") & IO
col = 0

 With ActiveSheet.ListObjects(sTableName)
    'find the last row of the list
    lLastRow = ActiveSheet.ListObjects(sTableName).ListRows.Count
    'shift from an extra row if list has header
    If .Sort.Header = xlYes Then
        iHeader = 1
    Else
        iHeader = 0
    End If
End With
'add the data a row after the end of the list
ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = sText

End Function

1 个答案:

答案 0 :(得分:1)

Public Function Appendtxt(IO As String)
Dim sql As String
sql = "INSERT INTO tbl ( [timestamp], var ) " & _
"SELECT #" & Time() & "#, """ & IO & """ AS Expr2"

DoCmd.RunSQL sql

End Function

假设你在这里发布一段excel代码时犯了一个错误,这应该可以解决问题。

编辑:要删除任何警告消息,请在启动数据库时调用以下函数。

Function fncSetOptions()
    Application.SetOption "Confirm Action Queries", False
    Application.SetOption "Confirm Document Deletions", False
    Application.SetOption "Confirm Record Changes", False
    DoCmd.SetWarnings False
End Function