所以我有一個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的代碼嗎? –