Question

I have a table in excel that is populated through a connection to an Access database. I am trying to write a macro that allows you to delete individual rows from this table. I use an ADODB connection to pass the delete command to Access, which works fine. However, at the end of the macro I want to refresh the table in excel so that, upon completion of the macro, the deleted record will no longer appear in that table.

I have already set backgroundquery = False on the connection that populates the table, but it doesn't seem to make a difference in this case. I have used the application.wait command as a workaround but I'm looking for a better solution. Is there another way to hold off the table refresh until my delete queries have run?

My code is below:

Sub Delete_recipe()

'Set up query
Dim Recipe_ID As Integer
    Worksheets("Recipe Adder").Calculate
    Recipe_ID = Range("New_recipe_ID").Value

'Open data connection
Dim Cn As ADODB.Connection
Set Cn = New ADODB.Connection
Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tucker\Desktop\Recipe project\MURPH.xls;Extended Properties=Excel 8.0;" _
& "Persist Security Info=False"

'Execute delete query
Cn.Execute "Delete from Recipe_master IN 'C:\Users\Tucker\Desktop\Recipe project\MURPH.accdb' where Recipe_ID =" & Recipe_ID
Cn.Execute "Delete from Recipe_ingredients IN 'C:\Users\Tucker\Desktop\Recipe project\MURPH.accdb' where Recipe_ID =" & Recipe_ID
Cn.Execute "Delete from Recipe_instructions IN 'C:\Users\Tucker\Desktop\Recipe project\MURPH.accdb' where Recipe_ID =" & Recipe_ID

'Close connection
Cn.Close
Set Cn = Nothing

'Application.Wait (Now + TimeValue("0:00:06"))
ActiveWorkbook.Connections("Murph Ingredient").Refresh

'Clear data from cells
Range("New_recipe_name_merged").ClearContents
Range("Recipe_description").ClearContents
Range("New_recipe_ingredients").ClearContents
Range("New_recipe_instructions").ClearContents

End Sub

Thanks for your help

Was it helpful?

Solution

You need to execute asynchronously and wait for it to complete. Please note that it will slow you down if you wait for each command to execute until triggering the next.

cn.Execute sqlString, , adAsyncExecute
Do While cn.state = adStateOpen + adStateExecuting
    ' wait for command to finish
    ' perhaps show a status here
Loop

ActiveWorkbook.Connections("Murph Ingredient").Refresh

We have to check for a combination of states per the State Property documentation

You can use the State property to determine the current state of a given object at any time. The object's State property can have a combination of values. For example, if a statement is executing, this property will have a combined value of adStateOpen and adStateExecuting.

Further Reading:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top