“文件正在使用”消息停止运行Visual Basic Excel脚本的过夜
所以我有一个VBScript,我通过我的任务调度程序运行。 经过testing和日常运行,大约有50%的时间我在上class的时候看到这个错误:
然后,如果我点击“通知”程序,然后完成执行。 但是这并不能帮助我,因为它会使程序自动运行。 我为什么只发生在50%的时间内的假设是,当我点击通知程序正确执行并closures所有内容时,那么当它运行的第二天不能正确closuresAPG.xlsx
,那么当它运行的第二天它会产生相同的错误信息。
程序布局
- 打开一个主excel表来运行VBA脚本
- 打开文件列表1,1刷新实时数据连接,然后将excel表保存为
name_POSReport.xlsx
(即APG_POSReport.xlsx
) - closures文件,并移动到下一个文件。
我的想法是,即使我把报告保存为另一个文件,我是否还必须closures原始文件? 事实并非如此,但也许是这样。 所以我希望有一些澄清。
Visual Basic脚本:
Dim xlApp Dim xlBook Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Open("\\fileserver\homeshares\asweet\My Documents\POS Reports\POS Live Reports\runReport.xlsm", 0, False) xlApp.Run "executeUpdate" xlBook.Close xlApp.Quit Set xlBook = Nothing Set xlApp = Nothing
VBA代码
Public wb As Workbook Sub executeUpdate() ' Vendors will be specified later ' Dim vendors(0 To 12) As String Dim testArray(0 To 2) As String Dim path, savePath, ext As String Dim i, x, erow As Long Application.DisplayAlerts = False x = Sheets(1).Cells(Rows.Count, "A").End(xlUp).row + 1 path = "\\fileserver\homeshares\asweet\My Documents\POS Reports\POS Live Reports\" savePath = "\\fileserver\homeshares\asweet\My Documents\POS Reports\POS Live Reports\Monthly POS Report\" ext = ".xlsx" testArray(0) = "APG" testArray(1) = "Code" testArray(2) = "IPC" For i = LBound(testArray) To UBound(testArray) Cells(x, 1).FormulaR1C1 = Now Cells(x, 2).FormulaR1C1 = testArray(i) Cells(x, 3).FormulaR1C1 = "Fail" openBook path & testArray(i) & ext, testArray(i), True saveBookAs savePath & testArray(i) closeBook Cells(x, 3).FormulaR1C1 = "Pass" x = x + 1 Next i ThisWorkbook.Save Application.DisplayAlerts = True End Sub Sub openBook(ByVal fileName As String, ByVal baseName As String, ByVal refresh As Boolean) Set wb = Workbooks.Open(fileName, 0, False) If refresh = True Then If Application.ProtectedViewWindows.Count > 0 Then Application.ActiveProtectedViewWindow.Edit End If wb.Connections(baseName & " POS Report").OLEDBConnection.BackgroundQuery = False wb.RefreshAll wb.Connections(baseName & " POS Report").OLEDBConnection.BackgroundQuery = True End If End Sub Sub closeBook() wb.Close End Sub Sub saveBookAs(ByVal fName As String) wb.SaveAs fileName:=fName & "_posReport.xlsx" End Sub
您可以调用VBA的运行时间方法,以便在程序运行后closuresexcel。 我假设你已经保存(或closures)了包含你的excecuteUpdate过程的工作簿。
你将需要一个程序来调用closuresexcel例如:
Sub excelQuit() Application.Quit End Sub
在你的executeUpdate过程中调用ontime方法
Call Application.OnTime((Now + TimeValue("00:00:10")), "excelQuit")
这将试图在通话完成10秒后closures应用程序,但是它将等待直到任何活动的过程首先完成。
我遇到过同样的问题。 但是我发现了一个工作。 基本上我创build了一个文件夹,并使用shutil复制文件来创build所需文件的副本。 之后,我运行我的pywin32脚本并删除副本。 这将停止显示消息。