Question : Deleting records using ADO recordsets in VBA

I'm having an incompatability with my code and SQL Server so I rewrote the sub using an ADO approach.  I get the following error:
   Run-time error '3219': Operation is not allowed in this context.

Note: The code that I commented out is my old code that worked with Access back-end.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
Private Sub DeleteInvRecord()
'Delete the Inventory record for lot # and package # if User deletes the Receiving record
'  Dim rstInv As Recordset
'  Dim strSQLDelete As String
  Dim rstInv As New ADODB.Record
  Dim cnn As New ADODB.Connection
  Dim strActiveConnection As String
  Dim strSQLServer As String
  Dim strDB As String
  Dim strQuery As String
  
'  strSQLDelete = "DELETE * FROM INVENTORY" & _
'                 " WHERE [Lot_Num] = " & "'" & sLotPack(i).strDeletedLot & "'" & _
'                 " AND [Package_Num] = " & sLotPack(i).intDeletedPack
'  CurrentDb.Execute strSQLDelete
  strSQLServer = "Mspm1bdbd54\a1"  'temp, if works will get server and db from dbConfig table TBD
  strDB = "DTLData"
  strActiveConnection = "Provider=SQLOLEDB;Data Source=" & strSQLServer & ";Initial Catalog=" & strDB & ";Integrated Security=SSPI"
  cnn.Open strActiveConnection
  strQuery = "SELECT Lot_Num FROM INVENTRY" & _
                 " WHERE [Lot_Num] = " & "'" & sLotPack(i).strDeletedLot & "'" & _
                 " AND [Package_Num] = " & sLotPack(i).intDeletedPack
  rstInv.Open strQuery, cnn, adOpenKeyset, adLockOptimistic
  With rstInv
    If Not .EOF Then
      .DeleteRecord
    End If
  End With
End Sub
Open in New Window Select All

Answer : Deleting records using ADO recordsets in VBA

Though ADO is flexible enough to allow you to perform actions through a recordset opening statement (incase the RDBMS supports multiple statements) it's never a good idea.
(However it's not a good practice at all.  If you ever had such a need then an SP which performed the actions and then returned the recordset would be appropriate).

You should execute the command through a command object - or against the connection directly.

cnn.Execute strSQLDelete

If you still get an error then post back.

Random Solutions  
 
programming4us programming4us