I want to insert Values to access table by using VBA control is there is any simple way to do this. i try this code but it does not work properly if i run this code it give the error 'variable not set' can anyone help me. thanks in advance
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
You are working in Access, so it is best to use DAO as it is native. Consider:
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
Against:
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
If your ADO example is inserting into the current database, it can be considerably simplified.
Note that:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.