Excel VBA无法保存包含variables保留date值的文件名

我有一些代码将当前工作表复制并粘贴到一个空白的新工作簿,然后根据某些单元格(存储在variables中)的值进行保存。

具体来说,这些是网站,客户和访问date。

这一切都与网站和客户端正常工作,但是,当我在文件名中包含datevariables保存,它会引发错误:运行时错误76 – 找不到path。

我会很感激任何帮助/build议。

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 

在文件名中使用date时,绝对不要依赖date的默认文本表示,因为这取决于当前的语言环境。

您应该将date作为date存储在首位,并以文件名的安全方式显式格式化:

 Dim visitdate As Date visitdate = Range("b7").Value dim visitdate_text as string visitdate_text = Format$(visitdate, "yyyy\-mm\-dd") 

您也可以考虑从您的其他值(如clientsite删除任何特殊字符。 否则,问题可能会再次出现。

这是我的代码重写的build议:

 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