0

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

具体来说,这些是站点、客户和访问日期。

这一切都适用于站点和客户端,但是当我在要保存的文件名中包含日期变量时,它会引发错误:运行时错误 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
4

2 回答 2

2

在文件名中使用日期时,您永远不想依赖日期的默认文本表示,因为这取决于当前的语言环境。

您应该首先将日期存储为日期,并以安全的方式明确格式化文件名:

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

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

您还可以考虑\从其他值中删除任何特殊字符,例如clientand site。否则问题可能会再次出现。

于 2013-03-18T12:08:51.430 回答
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
于 2013-03-18T12:20:11.027 回答