
在我使用的腳本中我有
Sub Saveaspdfandsend()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Set xSht = ActiveSheet
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
xFolder = xFolder + "\" + xSht.Name + Format(Now, " yyyy-mm-dd hmmAM/PM") + ".pdf"
'Check if file already exist
If Len(Dir(xFolder)) > 0 Then
xYesorNo = MsgBox(xFolder & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", _
vbYesNo + vbQuestion, "File Exists")
On Error Resume Next
If xYesorNo = vbYes Then
Kill xFolder
Else
MsgBox "if you don't overwrite the existing PDF, I can't continue." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"
Exit Sub
End If
If Err.Number <> 0 Then
MsgBox "Unable to delete existing file. Please make sure the file is not open or write protected." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"
Exit Sub
End If
End If
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
'Save as PDF file
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder, Quality:=xlQualityStandard
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.CC = "[email protected]"
.Subject = xSht.Name + ".pdf"
.Attachments.Add xFolder
If DisplayEmail = False Then
'.Send
End If
End With
Else
MsgBox "The active worksheet cannot be blank"
Exit Sub
End If
End Sub
這將顯示 2018 04 06 245PM。我嘗試在 h 和 mm 之間放置一個 : ,但運行腳本時出現錯誤。我可以使用空格或 .但不是:這不可能嗎?
答案1
在 Windows 中,檔案名稱不能包含字元:
。這就是當您嘗試儲存檔案時出現運行時錯誤的原因。
您還應該使用 24 小時格式,而不是 AM/PM:hhmm
對我來說更安全。
答案2
為了獲得正確的日期和時間戳,您的 VB 命令列應該是:
Format(now(), "yyyy-MM-dd hh:mm:ss")
或者
Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
注意:DateTime.Now
傳回資料類型為 Date 的值。日期變數會根據系統上設定的短日期和時間格式顯示日期。
若要顯示 AM/PM,請將格式字串變更為:
Format(TimeValue(Now), 'hh:mm AM/PM')