我有一個令人沮喪的時間嘗試在VBA中創建備份腳本。嘗試在打開文件後終止文件時發生錯誤「文件未找到」,進行備份並將其保存爲新名稱。文件未找到VBA
Application.Workbooks.Open Old
ActiveWorkbook.SaveAs Archive
ActiveWorkbook.SaveAs New
'If Len(Dir$(Old)) > 0 Then Kill Old
If Len(Dir$(Old)) = 0 Then MsgBox ("bleuh")
'Here is where I get the message "Bleuh" even though Old was just opened a few lines ago..
第一行工作正常,但是當我想殺死文件'舊'時,我得到錯誤。因此,我試圖測試文件是否存在。結果是Msg「Bleuh」。所以文件可以打開,但幾行後沒有找到。任何人都可以解釋這個並幫助我嗎?
爲了完整,整個代碼在這裏找到。
Sub UpdateAll()
Dim Afk As String, J As String, NJ As String, Path As String, strFile As String, Old As String, Archive As String, New As String
'Dim fso As Object
Path = "C:\Users\Name\OneDrive - Company\Desktop\Testing backup" & "\"
Year = Year(Date)
VJ = Year
NJ = Year + 1
Application.ScreenUpdating = False
'test for Afk (I define Afk for some additional functions that are not relevant for this problem)
Afk = "ABA"
'filenames
Old = Path & ("Planning ") & VJ & Space(1) & Afk
Archive = Path & ("Planning\Archive ") & VJ & Space(1) & Afk
New = Path & ("Planning ") & NJ & Space(1) & Afk
Application.Workbooks.Open Old
ActiveWorkbook.SaveAs Archive
ActiveWorkbook.SaveAs New
If Len(Dir$(Oud)) > 0 Then Kill Old
If Len(Dir$(Oud)) = 0 Then MsgBox ("bleuh")
'Here is where I get the message "Bleuh" even though Old was just opened a few lines ago..
'Also tried
'fso.CopyFile Old, Archive 'AND
'FileCopy Old, Archive
'in combination with:
'Name Old As New
' "SSDD"
'Next
Application.ScreenUpdating = True
End Sub
請問您的文件名可變有分機嗎? – braX
我沒有看到你指定路徑和文件名到'Oud'的位置。 – Jeeped
您先刪除文件,然後驗證它是否仍然存在...嘗試使用「Select Case」選項... – Pspl