我有一些代码将当前工作表复制并粘贴到一个空白的新工作簿中,然后根据某些单元格的值(存储在变量中)保存它。
具体来说,这些是访问过的网站,客户和日期。
这一切都适用于网站和客户端,但是当我在文件名中包含日期变量进行保存时,会抛出错误:运行时错误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
答案 0 :(得分:2)
在文件名中使用日期时,您永远不想依赖日期的默认文本表示,因为这取决于当前的语言环境。
您应该首先将日期存储为日期,并以安全的方式为文件名明确格式化:
Dim visitdate As Date
visitdate = Range("b7").Value
dim visitdate_text as string
visitdate_text = Format$(visitdate, "yyyy\-mm\-dd")
您还可以考虑从其他值中删除\
等任何特殊字符,例如client
和site
。否则问题可能会再次出现。
答案 1 :(得分: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