Excel VBA:运行时错误1004:Excel无法访问文件

时间:2018-11-05 02:19:21

标签: excel vba

我正在创建报告生成器的宏,该宏允许用户将文件的副本保存到目标位置。

单元格值(“ 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

但是,我遇到运行时错误时遇到了一些问题: enter image description here

我已经尝试过如下操作:

  • 调试并搜索SO,但找不到其他遇到相同问题的人
  • 我已经在所需位置创建了文件夹
  • 取消选中文件的“只读”复选框,以便可以对其进行写入

谢谢。

2 个答案:

答案 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