Deleting data from Access with VBA

dan picture dan · Oct 9, 2012 · Viewed 36.5k times · Source

I'm trying to delete every record from my current Access database in VBA where OTP = txtOTP.value and VARIABLE = {NomAdminContrats,TelAdminContrats,TelecAdminContrats, [...]}

Here is my code:

Dim query As Recordset 
Set query = CurrentDb.Execute("DELETE * FROM tb_SOMMAIRE WHERE OTP = '" & txtOTP.value & "' AND (VARIABLE = 'NomAdminContrats' or VARIABLE = 'TitreAdminContrats' or VARIABLE = 'UnitAdminContrats' or VARIABLE = 'AdrAdminContrats' or  VARIABLE = 'VilleAdminContrats' or VARIABLE = 'TelAdminContrats' or VARIABLE = 'TelecAdminContrats' or VARIABLE = 'CourrielAdminContrats')")

I got an error 3219 Invalid Operation when trying with OpenRecordset or Expected function when trying with Execute. I've tried a lot of things but I didn't manage yet to get this query working. I also have the full table in a recordset, would it be easier/faster to do it with myRecordset.Delete? If so, how could I do it?

EDIT

Now trying with CurrentDb.Execute instead of CurrentDb.OpenRecordset. The error is now Function expected instead of Invalid Operation.

Answer

HansUp picture HansUp · Oct 9, 2012

You already solved the problem. Congratulations. See whether a different approach for your WHERE clause is easier to work with.

The WHERE clause checks whether VARIABLE matches a list of values. Instead of using multiple OR conditions to compare VARIABLE with each member of the list, you can simply ask the db engine whether VARIABLE is present IN the list of values.

AND
    (
        [VARIABLE] IN
            (
                'NomAdminContrats',
                'TitreAdminContrats',
                'UnitAdminContrats',
                'AdrAdminContrats',
                'VilleAdminContrats',
                'TelAdminContrats',
                'TelecAdminContrats',
                'CourrielAdminContrats'
            )
    )