usando la fecha y hora adecuadas en el script

usando la fecha y hora adecuadas en el script

En el script que estoy usando tengo

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

que mostrará 2018 04 06 245PM. Intenté poner un : entre h y mm pero me da un error al ejecutar el script. Puedo usar un espacio o un . pero no un: ¿No es esto posible?

Respuesta1

En Windows, los nombres de archivos no pueden contener el carácter :. Es por eso que hay un error de tiempo de ejecución cuando intenta guardar el archivo.

También deberías usar un formato de 24 horas, en lugar de AM/PM: hhmmme parece más seguro.

ControlarFunción de formato (Visual Basic para aplicaciones)para más información.

Respuesta2

Para obtener una marca de fecha y hora adecuada, su línea de comando de VB debe ser,

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

o

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

Nota: DateTime.Nowdevuelve un valor de tipo de datos Fecha. Las variables de fecha muestran las fechas de acuerdo con el formato corto de fecha y hora establecido en su sistema.

Para mostrar AM/PM, cambie su cadena de formato a esto:

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

información relacionada