我正在创建报告生成器的宏,该宏允许用户将文件的副本保存到目标位置。
单元格值(“ E5”)是用户输入日期的地方。 单元格值(“ E11”)是用户键入记录名称的位置(在这种情况下为颜色值)
宏会将其保存到C驱动器中的位置
下面是代码:
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
谢谢。
答案 0 :(得分:1)
“文件名不能包含以下任何字符:\ /:*?” <> |“-您的文件名似乎是” 5 \ 11 \ 4192C700“,这实际上意味着您正在尝试将文件保存在一个不存在的目录c:\ Colour Log \ 5 \ 11 \ 4192C700。您必须在文件名中更改其他字符的斜杠。
答案 1 :(得分:1)
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