我在excel中有一个通过与Access数据库的连接填充的表。我正在尝试编写一个宏,允许您从该表中删除单个行。我使用ADODB连接将delete命令传递给Access,效果很好。但是,在宏末尾,我想在excel中刷新表,以便在宏完成后,删除的记录将不再出现在该表中。
我已经在填充表的连接上设置了backgroundquery = False,但在这种情况下似乎没有什么不同。我已经将application.wait命令用作解决方法,但是我正在寻找更好的解决方案。在我的删除查询运行之前,还有另一种方法可以推迟表刷新吗?
我的代码如下:
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
谢谢你的帮助
最佳答案
您需要异步执行并等待其完成。
请注意,如果您等待每个命令执行直到触发下一个命令,它将使您减速。
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
我们必须根据State Property documentation检查状态的组合
您可以使用State属性来确定当前状态
给定对象在任何时间。对象的State属性可以具有
价值组合。例如,如果一条语句正在执行,则此
属性将具有adStateOpen和的组合值
adStateExecuting。
进一步阅读:
ExecuteMethod
Option State Enum