将数据从vba插入表中

时间:2013-12-21 00:05:26

标签: ms-access access-vba

我找到了以下VBA代码来生成`sCode字符串。

但如何将sCode插入Table1

我是 MS Access 编程的新手。

Private Sub Command120_Click()
 Dim sCode As String
   Dim i As Long
   For i = 1 To Me.Qty
      sCode = Format(Now(), "YYMMDDHHNNSS") & Format(i, "0000")
   Next i
End Sub

1 个答案:

答案 0 :(得分:1)

至少有两种方式 - 在这两种方式中我都假设字段本身称为sCode ...

1)使用DAO:

Private Sub Command120_Click()
  Dim RS AS DAO.Recordset, sCode As String, i As Long
  Set RS = CurrentDb.OpenRecordset("Table1")
  For i = 1 To Me.Qty
    sCode = Format(Now(), "YYMMDDHHNNSS") & Format(i, "0000")
    RS.AddNew
    RS!sCode = sCode
    RS.Update
  Next i
End Sub

2)使用SQL语句:

Private Sub Command120_Click()
  Dim DB AS DAO.Database, sCode As String, i As Long
  Set DB = CurrentDb
  For i = 1 To Me.Qty
    sCode = Format(Now(), "YYMMDDHHNNSS") & Format(i, "0000")
    DB.Execute("INSERT INTO Table1 (sCode) VALUES ('" + sCode + "')");
  Next i
End Sub

如果你想确定在发生错误时没有任何更新,你可能还想在事务中包装。