我想通过使用VBA控件插入值来访问表是否有任何简单的方法来执行此操作。我尝试这个代码但它不能正常工作如果我运行此代码它给错误'变量未设置'任何人都可以帮助我。提前谢谢
Private Sub CommandButton1_Click()
Dim cn As ADODB.Connection
Dim strSql As String
Dim lngKt As Long
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
Dim myRecordset As New ADODB.Recordset
Dim SQL As String, SQL2 As String
dbPath = "table.accdb"
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
SQL = "INSERT INTO Jun_pre (ProductName,DESCRIPTION,SKU,MT,(mt),MRP,Remark,no_of_units_in_a_case) VALUES (""aa"",""bb"",""test"",""testUnit"",""1"",""2"",,""3"",,""4"");"
With cnt
.Open dbConnectStr 'some other string was there
.Execute (SQL)
.Close
End With
End Sub
答案 0 :(得分:5)
您正在使用Access,因此最好使用DAO,因为它是原生的。考虑:
Private Sub CommandButton1_Click()
Dim sSQL As String
sSQL = "INSERT INTO Jun_pre " _
& "(ProductName,DESCRIPTION,SKU,MT,(mt),MRP,Remark," _
& "no_of_units_in_a_case) VALUES "
& "(""aa"",""bb"",""test"",""testUnit"",1,2,Null,3,Null,4);"
CurrentDB.Execute sSQL, dbFailOnError
End Sub
反对:
Private Sub CommandButton1_Click()
Dim cn As New ADODB.Connection
Dim strSql As String
Dim lngKt As Long
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
''You do not need a recordset to execute an SQL statement
''Dim myRecordset As New ADODB.Recordset
Dim SQL As String, SQL2 As String
dbPath = "table.accdb"
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
strSQL = "INSERT INTO Jun_pre " _
& "(ProductName,DESCRIPTION,SKU,MT,(mt),MRP,Remark," _
& "no_of_units_in_a_case) VALUES "
& "(""aa"",""bb"",""test"",""testUnit"",1,2,Null,3,Null,4);"
With cnt
.Open dbConnectStr 'some other string was there
.Execute (strSQL)
.Close
End With
End Sub
如果您的ADO示例正在插入当前数据库,则可以大大简化它。
请注意: