【问题标题】:Saving a file as a date将文件另存为日期
【发布时间】:2020-10-18 14:15:29
【问题描述】:

我正在导入日常数据并对其进行操作。我想将文件保存为从 A4 中提取的数据的日期。

我收到的数据最初是 CSV 文件,格式为 27/06/2020。我在操作过程中重新格式化了数据,但不管怎样,当我保存文件时,我得到了一个

运行时错误 1004 Microsoft Excel 无法访问文件 "C:\Users\steve\Desktop\27\06\D2D75130"

我不清楚是否(以及如何)将其更改为文本格式以便保存 - 但我喜欢将日期保持为日期格式以帮助我进行数据分析的想法。或者也许我应该在日期前添加一个文本字符串,即“销售(然后是日期)”——如果这样可行?这是我现有的代码:

' This is to save the file on the desktop using the date (content of cell A4) as the filename
' It also saves the file with the name 'Latest Report' in the Reports Folder


Sub FileNameAsCellContent()

    Dim FileName As String
    Dim Path As String
    Application.DisplayAlerts = False
    Path = "C:\Users\steve\Desktop\" 'change this if you want to save it somewhere else
    FileName = Sheets("Summary").range("A4").Value & ".xlsm"

    ActiveWorkbook.SaveAs Path & FileName, xlOpenXMLWorkbookMacroEnabled

    ' Change the format here which matches with the extention above. Choose from the following link
    ' http://msdn.microsoft.com/en-us/library/office/ff198017.aspx

    Application.DisplayAlerts = True


    ' This saves it in the reports folder as 'Latest Report'

    ChDir "C:\Users\steve\Desktop\Reports"
    ActiveWorkbook.SaveAs FileName:= _
    "C:\Users\steve\Desktop\Reports\Latest Report.xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub

【问题讨论】:

  • 对不起,应该是这样的:运行时错误 1004 Microsoft Excel 无法访问文件“C:\Users\steve\Desktop\27\06\D2D75130”
  • Sheets("Summary").range("A4").Value is 27/06/2020
  • msgbox 将文件名显示为 27/06/2020.xlsm

标签: excel vba date format filenames


【解决方案1】:

如果Sheets("Summary").range("A4").Value 中有一个/ 字符,您需要先替换或删除它,因为该字符不能在文件名中使用。请改用以下行来删除该字符。

FileName = Replace(Sheets("Summary").range("A4").Value, "/", "") & ".xlsm" 

您也可以将其替换为新的有效字符:

FileName = Replace(Sheets("Summary").range("A4").Value, "/", "-") & ".xlsm" 

Replace function VBA Documentation

这是所有非法字符的列表:

Remove illegal characters while saving workbook Excel VBA

【讨论】:

  • 一个更易于理解的答案可能包括(或引用)所有非法字符(用于文件名)。
猜你喜欢
  • 2018-07-08
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多