2013-03-18 117 views
0

我有一些代碼將當前工作表複製並粘貼到空白的新工作簿,然後根據某些單元格(存儲在變量中)的值進行保存。Excel VBA無法保存具有變量保留日期值的文件名

具體來說,這些是網站,客戶和訪問日期。

這一切都與網站和客戶端正常工作,但是當我在文件名中包含日期變量保存時,它會引發錯誤:運行時錯誤76 - 找不到路徑。

我會很感激任何幫助/建議。

Sub Pastefile() 

Dim client As String 
Dim site As String 
Dim visitdate As String 
client = Range("B3").Value 
site = Range("B23").Value 
screeningdate = Range("B7").Value 

Dim SrceFile 
Dim DestFile 

SrceFile = "C:\2013 Recieved Schedules\schedule template.xlsx" 
DestFile = "C:\2013 Recieved Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx" 

FileCopy SrceFile, DestFile 

ActiveWindow.SmallScroll Down:=-12 
Range("A1:I37").Select 
Selection.Copy 
ActiveWindow.SmallScroll Down:=-30 
Workbooks.Open Filename:= _ 
    "C:\Schedules\2013 Recieved Schedules" & "\" & client & " " & site & " " &  visitdate & ".xlsx", UpdateLinks:= _ 
0 
Range("A1:I37").PasteSpecial Paste:=xlPasteValues 
Range("C6").Select 
Application.CutCopyMode = False 
ActiveWorkbook.Save 
ActiveWindow.Close 

End Sub 
+1

如果日期中包含'/',他們將被解釋爲路徑的一部分。什麼'msgbox「C:\ Schedules \ 2013收到時間表」&「\」&客戶端&「」&網站&「」&visitdate&「.xlsx」'看起來像 – 2013-03-18 12:00:04

+0

啊,你是對的,謝謝你的擡頭。我已經確定這些格式化爲例如「2013年1月1日」,但假設它不會讓我絆倒。我怎樣才能避免這個問題?謝謝。 – user1571463 2013-03-18 12:07:57

+0

嗨。事實上,你的代碼看起來有缺陷。你是否看到你提到了screeningdate,而不是他上面聲明的變量visitdate?使用Debug Step-By-Step(F8)而不是使用F5來徹底檢查它是很好的。希望這個想法有點幫助你做更好的編碼:-) – Octopus 2013-03-18 12:11:25

回答

2

使用文件名中的日期,你永遠要依靠日期的默認文字表述,因爲這取決於當前的語言環境。

你應該保存日期日期擺在首位,並明確在爲文件名以安全的方式格式化:

Dim visitdate As Date 
visitdate = Range("b7").Value 

dim visitdate_text as string 
visitdate_text = Format$(visitdate, "yyyy\-mm\-dd") 

你也可以考慮去除像\從您的其他值的任何特殊字符如clientsite。否則,問題可能會再次出現。

+0

感謝您的幫助球員,這兩個問題已得到糾正,現在一切正常。 – user1571463 2013-03-18 12:13:59

+0

永遠歡迎! :-) – Octopus 2013-03-18 12:45:45

0

這裏是我的代碼重寫的建議:

Sub Pastefile() 

Dim client As String 
Dim site As String 
Dim visitdate As String 
client = Range("B3").Value 
site = Range("B23").Value 
visitdate = Range("B7").Value 

Dim SrceFile 
Dim DestFile 

If IsDate(visitdate) Then 

SrceFile = "C:\2013 Received Schedules\schedule template.xlsx" 
DestFile = "C:\2013 Received Schedules" & "\" & Trim(client) & " " & Trim(site) & " " & Str(Format(Now(), "yyyymmdd")) & ".xlsx" 

If Trim(Dir("C:\2013 Received Schedules\schedule template.xlsx")) <> "" Then 
FileCopy SrceFile, DestFile 
Else 
MsgBox (SrceFile & " is not available in the folder") 
GoTo EndCode 
End If 

Range("A1:I37").Select 
Selection.Copy 

Workbooks.Open Filename:= _ 
"C:\Schedules\2013 Received Schedules" & "\" & client & " " & site & " " & visitdate & ".xlsx", UpdateLinks:= 0 
Range("A1:I37").PasteSpecial Paste:=xlPasteValues 
Range("C6").Select 
Application.CutCopyMode = False 
ActiveWorkbook.Save 
ActiveWindow.Close 

Else 
MsgBox ("Please input the correct date in cell B7") 
ActiveSheet.Range("B7").Activate 
End If 
EndCode: 
End Sub