簡體   English   中英

訪問 VBA(打開 excel 文件並關閉):關閉“文件現在可用”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM