【发布时间】: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 & "_" & Format(strDate,"dd-mm-yyyy") & ".pdf" -
完美运行!不过这很容易......非常感谢!