[英]Excel VBA : Run Time Error 1004 : Excel cannot access to file
I am creating a macro of the report generator that let the user to save a copy of the file to its destination. 我正在创建报告生成器的宏,该宏使用户可以将文件的副本保存到其目标位置。
Cell value ("E5") is where the user input the date. 单元格值(“ E5”)是用户输入日期的地方。 Cell value ("E11") is where user keyin the record name (in this case colour values)
单元格值(“ E11”)是用户键入记录名称的位置(在这种情况下为颜色值)
The macro will save it to the location in the C drive 宏会将其保存到C驱动器中的位置
Here are the code : 这是代码:
Sub CTemplate()
'Select up the macro generator
Sheets("File Generator").Select
'Save file according to the textbox values
Dim filename As String
Dim varDatevalue As String
Dim varColourvalue As String
varDatevalue = Range("E5").Value
varColourvalue = Range("E11").Value
ActiveWorkbook.SaveAs filename:="C:\Colour Log\" & varDatevalue & "--" & varColourvalue & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
However, there are some problems as I encounter to run time error: 但是,当我遇到运行时错误时会遇到一些问题:
Thank you . 谢谢 。
“文件名不能包含以下任何字符:\\ /:*?“ <> |”-您的文件名似乎是“ 5 \\ 11 \\ 4192C700”,这实际上意味着您试图将文件保存在非目录c:\\ Colour Log \\ 5 \\ 11 \\ 4192C700。您必须在文件名中更改其他字符的斜杠。
Sub CTemplate()
'Always place values, especially text into constants, so you can
'quickly change them and you don't have to search and change them
'wherever they appear in the code.
Const cStrPath As String = "C:\Colour Log\"
Const cStrWsName As String = "File Generator"
Const cStrDateCell As String = "E5"
Const cStrColorCell As String = "E11"
Dim arrNope As Variant
Dim strNope As String
Dim strFileName As String
Dim strDate As String
Dim strColour As String
Dim intNope As Integer
'Characters you can't have in a filename
strNope = "\ / : * ? < > | [ ] " & Chr(34) 'Chr(34) is double quotes (")
'You can add other characters like "." if you don't want them in the
'filename, just make sure to separate the characters and end the string
'with a space (" ").
'Paste the characters into an array
arrNope = Split(strNope)
'Calculate strings
With Worksheets(cStrWsName)
'Loop through the array of characters
For intNope = LBound(arrNope) To UBound(arrNope)
'With 'Cstr' you coerce each value to a string data type.
'With 'Replace' you replace each character with "", practically you
'delete each 'unwanted' character if it is found.
strDate = Replace(CStr(.Range(cStrDateCell).Value), _
arrNope(intNope), "")
Next
'Coerce the value to a string datatype
strColour = CStr(.Range(cStrColorCell).Value)
End With
'Calculate filename
strFileName = cStrPath & strDate & "--" & strColour & ".xlsm"
'The following line is used only to suppress the error that could occur when
'a file already exists and at the prompt "No" or "Cancel" is selected.
On Error Resume Next
'Save the file
ActiveWorkbook.SaveAs filename:=strFileName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.