【问题标题】:Changing Date format when saving as PDF另存为 PDF 时更改日期格式
【发布时间】:2019-11-20 12:30:18
【问题描述】:

我遇到了以下问题:
我想使用 VBA 将工作表保存为 PDF。文件名应包含一些单元格的值,包括一个包含日期的单元格。该日期已更改为“dd-mm-yyyy”格式(通过代码或“主页”选项卡中的“数字格式”下拉菜单),因为文件名不能包含“/”,但当我查看公式栏时,日期仍然是"dd/mm/yyyy"。

运行代码时,文件名以该格式返回日期... 如何更改日期格式,以便可以将其正确包含在文件名中?


Dim wsA As Worksheet
Dim wbA As Workbook
Dim strDate As Range
Dim strName As Range
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler

Set wbA = ActiveWorkbook
Set wsA = ActiveWorkbook.Sheets("Devis")
Set strName = ActiveWorkbook.Sheets("Calc").Range("Designation")
Set strDate = ActiveWorkbook.Sheets("Calc").Range("arrival")

strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strDate = Replace(strDate, "/", "-")

strFile = strName & "_" & strDate & ".pdf"
strPathFile = strPath & strFile

myFile = Application.GetSaveAsFilename _
    (InitialFileName:=strPathFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and FileName to save")

If myFile <> "False" Then
    wsA.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=myFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    'confirmation message with file info
    MsgBox "PDF file has been created: " _
      & vbCrLf _
      & myFile
End If

exitHandler:
    Exit Sub
errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler


End Sub

您会看到我尝试在代码中将“/”替换为“-”,但这似乎没有帮助... 期待您的建议!

【问题讨论】:

  • 试试strFile = strName &amp; "_" &amp; Format(strDate,"dd-mm-yyyy") &amp; ".pdf"
  • 完美运行!不过这很容易......非常感谢!

标签: excel vba date


【解决方案1】:

当您使用strDate = Replace(strDate, "/", "-") 时,您正在调用单元格中的值。即使您在上面看到日期,Excel 上的日期实际上也是数字。

所以Replace(strDate, "/", "-") 不起作用,因为没有什么可以替换的。

使用Format 可以更改值的显示方式,您可以将新格式化的值保存到字符串变量中。

这就解释了为什么strFile = strName &amp; "_" &amp; Format(strDate,"dd-mm-yyyy") &amp; ".pdf" 有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多