2017-09-22 120 views
0

我有一個令人沮喪的時間嘗試在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 
+1

請問您的文件名可變有分機嗎? – braX

+1

我沒有看到你指定路徑和文件名到'Oud'的位置。 – Jeeped

+1

您先刪除文件,然後驗證它是否仍然存在...嘗試使用「Select Case」選項... – Pspl

回答

0

分析你的代碼後,我意識到你不需要打開你的文件(因爲你沒有得到任何信息)。你只是想要移動它。所以,請嘗試以下操作:它

Name Old as Archive 

這應該做的伎倆......

+0

感謝您的幫助,雖然它不能解決問題。我得到了同樣的錯誤'找不到文件'。 – Eelco

+0

如果文件路徑和名稱真的正確,你可以用'MsgBox Old'命令驗證嗎?如果該文件真的在您指定的文件夾中? – Pspl

+0

我使用名稱正確的msgbox對其進行驗證,並以可視方式檢查文件是否位於指定文件夾中。此外,該文件在Application.Workbooks.Open Old行中打開,所以我非常確定文件路徑和名稱是正確的 – Eelco