How can I use VBA to turn a file name into a date time code? (11-25-21 1530 to 11/25/21 15:30)

I have been working on a project where I am using a macro to load an excel file, pull some data from it, and paste it into a log file. Each of the source excel files are named by the sample date time it was created. For instance, a sample created November 25th, 2021 at 3:30 PM would have the file name "11-25-21 1530". When I load this file in the macro, I want to pull the file name, assign it to a variable, and format that string into the date time format recognized by excel for plotting (11/25/21 15:30). I cannot change the file names to include the "/" or ":" since these are not valid in file names.

I have done something similar using a userform for time only where it autoformats into a 24hr time variable, code below:


   'Input would be HHMM or HMM

    Dim a As String
    a = Len(Me.TextBox2)
    If a <= 2 Then 'This is for cases with H or HH
    On Error Resume Next
    Me.TextBox2 = Left(Me.TextBox2, a) & ":" & 0 
    ElseIf a = 3 Then
    Me.TextBox2 = Left(Me.TextBox2, 1) & ":" & Right(Me.TextBox2, 2) 'This is for cases with HMM
    Else
        If Me.TextBox2.Value >= 2400 Then
        MsgBox ("Incorrect Value")
        Call CommandButton1_Click
    Else
    Me.TextBox2 = Left(Me.TextBox2, 2) & ":" & Right(Me.TextBox2, 2) 'This is for cases with HHMM
    End If
    
End If
    Me.TextBox2 = Format(Me.TextBox2, "HH:MM")
End Sub

I do not know how to take the file name and split it into a date and then a time, format both to the proper excel date time format, then combine them again for MM/DD/YY HH:MM output to log the results.

Thank you for any assistance.


Use simple string handling to split the name into it's pieces. Then use DateSerial and TimeSerial to create a real Date out if it.

Once that is done, you can do whatever you want with the Date. I don't understand your request "into the date time format recognized by excel for plotting (11/25/21 15:30)", I do know that my Excel will have a hard time to understand 11/25/21 correctly (I am not located in the US...). When you write the date into a cell, write it as date and format the cell. If you need it in your code as string, use the Format-command.

The following function will split a filename, just note that there is no error handling or plausability test.

Function FilenameToDate(filename As String) As Date
    Dim fileYear As Long, fileMonth As Long, fileDay As Long, fileHour As Long, fileMinute As Long
    
    fileDay = Val(Mid(filename, 4, 2))
    fileMonth = Val(Mid(filename, 1, 2))
    fileYear = Val(Mid(filename, 7, 2))
    fileHour = Val(Mid(filename, 10, 2))
    fileMinute = Val(Mid(filename, 13, 2))
    
    FilenameToDate = DateSerial(fileYear, fileMonth, fileDay) + TimeSerial(fileHour, fileMinute, 0)
    
End Function