スクリプトで適切な日付と時刻スタンプを使用する

スクリプトで適切な日付と時刻スタンプを使用する

私が使用しているスクリプトでは

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 では、ファイル名に 文字を含めることはできません:。そのため、ファイルを保存しようとすると実行時エラーが発生します。

AM/PM の代わりに 24 時間形式を使用することをお勧めします。hhmmその方が安全だと思います。

チェックフォーマット関数 (Visual Basic for Applications)詳細については。

答え2

適切な日付と時刻のスタンプを得るには、VB のコマンド ラインは次のようになります。

Format(now(), "yyyy-MM-dd hh:mm:ss")

または

Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")

注:DateTime.Now日付データ型の値を返します。日付変数は、システムで設定された短い日付と時刻の形式に従って日付を表示します。

AM/PM を表示するには、フォーマット文字列を次のように変更します。

Format(TimeValue(Now), 'hh:mm AM/PM')

関連情報