[英]Access VBA (open excel file and close): turn off "file now available"
我使用以下 Access VBA 代码在循环中打开四个不同的 excel 工作簿,同时我需要编辑 excel 数据,然后通过记录集更新 Access 表。
xl.Application.DisplayAlerts = False
Set wb = xl.Workbooks.Open(fileName, ReadOnly = True, editable = True, notify = False)
Set ws = wb.Sheets("Sheet1")
Set ws2 = wb.Worksheets.Add
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileName & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;"";"
*****其他代码*****
wb.Close savechanges:=False
Set wb = Nothing
Set xlc = Nothing
Set ws = Nothing
Set ws2 = Nothing
Set xl = Nothing
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
但是,即使我在没有保存所有四个文件的情况下关闭了 excel 文件,在完整循环后我仍然收到以下通知。
使用Set wb = xl.Workbooks.Open(fileName, ReadOnly = True, editable = True, notify = False)
,我仍然无法关闭通知。
附注。 我没有收到所有四个文件的读写通知,通常是一两个,这让我很困惑。
任何解决问题的建议?
在此先感谢所有帮助!
您无法在 VBA 中手动控制垃圾收集,但您可以构造数据,以便垃圾收集更可预测。 我建议的第一件事是将 Excel 互操作代码放入它自己的从主循环调用的过程中。 原因是当程序结束时,会发生垃圾收集。 下一次循环调用 open 过程时,您将使用一组新的对象句柄,而不是像当前那样回收对象。 如果你这样做,你永远不必将你的对象设置为空,因为它们在过程结束时超出范围时被销毁。 只要确保始终使用局部变量。
为了在不重复关闭和打开 Excel 的情况下执行此操作,您需要获取当前正在运行的 Excel 实例的句柄。 这是由下面的GetExcelApp
过程提供的。
例子:
Private Sub YourMainLoop()
For Each fileName in fileNames
ProcessExcelData fileName
Next fileName
End Sub
Private Sub ProcessExcelData(ByVal fileName as String)
Dim xl As Object
Set xl = GetExcelApp
xl.Application.DisplayAlerts = False
Set wb = xl.Workbooks.Open(fileName, ReadOnly = True, editable = True, notify = False)
Set ws = wb.Sheets("Sheet1")
Set ws2 = wb.Worksheets.Add
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileName & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;"";"
' Process the data, blah blah blah
wb.Close savechanges:=False
rs.Close
cn.Close
End Sub
Public Function GetExcelApp() As Object
' Returns open excel instance.
' If it doesn't exist, creates one to return
On Error GoTo ErrHandler
Const ERR_APP_NOTRUNNING As Long = 429
Set GetExcelApp = GetObject(, "Excel.Application")
CleanExit:
Exit Function
ErrHandler:
If Err.number = ERR_APP_NOTRUNNING Then
Set GetExcelApp = CreateObject("Excel.Application")
Resume CleanExit
Else
ShowErrorMessageBox
End If
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.