2014-08-28 513 views
0

我有一個(鏈接)表[Traffic],其中一個字段名爲[Log]
我有一個變量IO,可以是「I」或「O」。VBA在Access中添加新記錄

該函數的唯一目的是向包含一個字符串的[Log]列中的表[Traffic]添加一條新記錄/行:每次結合「I」或「O」的日期標記表單被加載/卸載。

我嘗試在Ms Access 2010中創建函數但未成功(錯誤:「Object Required」)。

任何幫助,高度讚賞。

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 
+2

您已經發布了EXCEL的代碼,而不是ACCESS – 4dmonster 2014-08-28 13:25:32

+0

在何處將數據添加到Access?我沒有看到這一點。 – PaulFrancis 2014-08-28 13:33:59

回答

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 
+0

感謝您的提示傢伙。這工作。你有什麼想法消除彈出消息「你即將追加1行」? – Xavier 2014-08-28 14:16:28

+0

已添加到答案。 – Jens 2014-08-28 14:19:48