所以我有一个VBScript,我通过我的任务调度程序运行。经过测试并每天运行,大约有50%的时间我在上午看到这个错误,当我开始工作时:“文件正在使用”消息停止过夜运行的Visual Basic Excel脚本
然后,如果我点击'通知'程序,然后完成执行。但是这并不能帮助我,因为它无法自动运行程序。我为什么只发生在50%的时间内的假设是,在我点击通知后,程序正常执行并关闭所有内容,然后当它运行的第二天没有正确关闭APG.xlsx
,那么第二天它运行时会产生相同的错误信息。
计划布局
- 打开主Excel工作表1运行VBA脚本
- 打开文件1列表刷新实时数据连接,然后在Excel工作表保存为
name_POSReport.xlsx
(即APG_POSReport.xlsx
) - 关闭文件,并移动到下一个文件。
我的想法是,即使我将报告另存为另一个文件,我是否还必须关闭原始文件?事实并非如此,但也许是这样。所以我希望能有所澄清。
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
这是由于工作簿是共享的。检查出http://office.microsoft.com/en-gb/excel-help/features-that-are-unavailable-in-shared-workbooks-HP005201080.aspx –
@PankajJaju那么为什么它不会发生每一次程序运行? – Adjit
没有工作簿没有共享,但我想,它已被另一个应用程序打开。你是否正确地关闭并清理excel对象?你能分享vbs的代码吗? –