Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Use time in hh:mm AM/PM format from imported .txt with VBA

0

Hi all! 

I`m glad I found this website for excel users! I had some trouble exctracting some time data from a text file which comes as d/mm/yyyy hh:mm:ss. I ideally, would like it to be only as h:mm:ss AM/PM (on the "extract time" sheet) and keep the original text files separately in the "import text" sheet. All this should be done by the click of the "import" button as seen in the attached file. Also, if possible, this should work with csv and/or xls files. Please, can someone tell me what line of coding I`m missing to solve this issue? Any help will be appreciated it!

P.S. I was able to use someone else`s code as a reference. Link:Import text files in excel within selected cells using VBA | TeachExcel.com

Sub import_txt()

    Dim command As Variant
    Dim fileFilterPattern As String
    Dim n As Long
    fileFilterPattern = "Text Files (*.txt; *.csv),*.txt;*.csv"
    command = Application.GetOpenFilename(fileFilterPattern)

    If command = False Then
        MsgBox "No selection."
        Exit Sub
    End If

    Application.ScreenUpdating = False

    Open command For Input As #1

    Do Until EOF(1)
        Line Input #1, command

        If Len(command) > 0 Then
            command = Replace(command, ",", Chr(9))
            command = Split(command, Chr(9))
            ActiveCell.Offset(n, 0).Resize(1, UBound(command) + 1).Value = command
        End If

        n = n + 1
    Loop

    Close #1

    Application.ScreenUpdating = True

    ' convert text numbers to numbers==================================
    For Each WS In Sheets
    On Error Resume Next
    For Each r In WS.UsedRange.SpecialCells(xlCellTypeConstants)
        If IsNumeric(r) Then r.Value = (r.Value) * 1
    Next r
Next WS
' format date and times?? ======================
   Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
        For Each r In Selection
            v = r.Text
            r.Clear
            r.NumberFormat = "dd/mm/yyyy hh:mm:ss"
            r.Value = DateSerial(Mid(v, 7, 4), Mid(v, 4, 2), Left(v, 2)) + TimeSerial(Mid(v, 12, 2), Mid(v, 15, 2), Right(v, 2))
        Next r
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub
Answer
Discuss

Discussion

Hi Isacri05 and thanks for asking a new question (as I requested in the linked previous question). 

It's late here but I'll try to find time tomorrow to reply. 
John_Ru (rep: 6142) May 3, '23 at 6:14 pm
Add to Discussion

Answers

0
Selected Answer

Isacri05

You haven't attached a  file so I can't see what form the dates are but you say they are "d/mm/yyyy hh:mm:ss" and you want (just) "h:mm:ss AM/PM". You can do by using VBA's CDate function to convert the text to a date/time (number) then format that number as text using VBA's Format function. You're left with a text string line "6:09:51 AM".

To do that, replace the code section below:

        For Each r In Selection
            v = r.Text
            r.Clear
            r.NumberFormat = "dd/mm/yyyy hh:mm:ss"
            r.Value = DateSerial(Mid(v, 7, 4), Mid(v, 4, 2), Left(v, 2)) + TimeSerial(Mid(v, 12, 2), Mid(v, 15, 2), Right(v, 2))
        Next r

with:

        For Each r In Selection
            r.Value = Format(CDate(r.Text), "h:mm:ss AM/PM")
        Next r

To retain the date/time number (e.g. for time calculations) but see only the time portion, use this instead:

        For Each r In Selection
            r.Value = CDate(r.Text)
            r.NumberFormat = "h:mm:ss AM/PM"
        Next r

Note that you shouldn't turn the speed-up measures (Application.ScreenUpdating,  .Calculation and .EnableEvents) on and off several times in your macro- just turn them off at the start then back on as you exit the sub. Very often they're not needed (e.g. for small data sets like yours). Fior more information, see Don's tutorial here: Guide to Making Your Macro Run Faster and Better in Excel

Revision 05 May 2023:

In the attached  revised version of the user's file, the following code will import both types of (embedded) text files and display dates aas AM/PM and number values as decimals. It's commented for your guidance:

Sub import_txt()

    Dim command As Variant
    Dim fileFilterPattern As String
    Dim n As Long

    On Error Resume Next

    fileFilterPattern = "Text Files (*.txt; *.csv),*.txt;*.csv"
    command = Application.GetOpenFilename(fileFilterPattern)

    If command = False Then
        MsgBox "No selection."
        Exit Sub
    End If

    Application.ScreenUpdating = False

    Open command For Input As #1
    ' ignore first line
    Line Input #1, command
    ' loop through lines
    Do Until EOF(1)
        Line Input #1, command
        ' check it's not empty
        If Len(command) > 0 Then
            ' if line is comma-separated, replace with tabs
            If InStr(command, ",") > 0 Then command = Replace(command, ",", Chr(9))
            ' create an array from tab-separated string
            command = Split(command, Chr(9))
            ' write to cells
            ActiveCell.Offset(n, 0).Resize(1, UBound(command) + 1).Value = command
            ' for date/ (second column)
            With ActiveCell.Offset(n, 1)
                ' convert to date and format display
                .Value = CDate(.Text)
                .NumberFormat = "h:mm:ss AM/PM"
                ' if 3 columns imp0rted...
                If UBound(command) = 2 Then
                ' ... convert next column along to a decimal and display to 3dp
                    .Offset(0, 1).Value = CDec(.Offset(0, 1).Value)
                    .Offset(0, 1).NumberFormat = "#,##0.000"
                End If
            End With
        End If

        n = n + 1
    Loop

    Close #1

    Application.ScreenUpdating = True

End Sub

To use it, select an empty cell with rows to the right and below empty then run the macro (selecting one of the sample files which should be saved out previously).

In the addtional sheet "TRIAL" there are examples of the imported data for each type.

REVISION 06 MAY 2023:

Seems the user really wants to use values already imported (as text) in worksheet "import text"  and show them in formatted cells in "extract time" without converting the values.

One way to do that is to use Excel's TIMEVALUE function and point to the imported text strings...

In the second attached file, cells A2:B12 in sheet "extract time" are already formatted to display as "h:mm:ss AM/PM" so TIMEVALUE works to convert time string, e.g. in cell A2 uses the formula

=TIMEVALUE('import text'!B3)

(and likewise down) and works for date/time strings, e.g. in B2

=TIMEVALUE('import text'!F3)

Hope this helps. If so,  please remember to return and mark this Answer as Selected.

Discuss

Discussion

hi John_Ru,
Thank you for spending your time on my problem. Unfortunately, it seems like the website won`t let me upload .txt files. Here are the copied text values/dates I want to upload: 
Sample 1: (imported on the left side of the "import text" tab)
MM/dd/yyyy,hh:mm:ss,Values 05/03/2023,06:05:35,0.003 05/03/2023,06:20:35,0.007 05/03/2023,06:35:35,0.005 05/03/2023,06:50:35,0.006 05/03/2023,07:05:35,0.005 05/03/2023,07:20:35,0.006 05/03/2023,07:35:35,0.006 05/03/2023,07:50:35,0.006 05/03/2023,08:05:35,0.006 05/03/2023,08:20:35,0.010
Sample 2: (on the right side of the "import text" tab)
ValuesDate/Time 001 5/3/2023 06:09:51 002 5/3/2023 06:24:51 003 5/3/2023 06:39:51 004 5/3/2023 06:54:51 005 5/3/2023 07:09:51 006 5/3/2023 07:24:51 007 5/3/2023 07:39:51 008 5/3/2023 07:54:51 009 5/3/2023 08:09:51 010 5/3/2023 08:24:51
Essentially, I want to keep both sets of data in the "import text" table and have a separate table on the "extract time" worksheet to exctract the date in the format of h:mm:ss AM/PM for time. But for some reason, I cannot get the AM/PM part from sample 1 and from sample 2 I'm still getting the date and time in the same cell instead of h:mm:ss AM/PM after using your code (unless I`m doing something wrong). 
Isacri05 (rep: 2) May 4, '23 at 8:49 am
The Forum only allows the upload of Excel files but you can embed text files ("as an icon") into an Excel file and upload that. I now see that you want to upload different data formats but don't know which data you need- while Sample 1 has a time/ value (in bold) but non-standard time format:
05/03/2023 06:05:35 0.003
is the data in Sample 2 at the start? E.g.:
001 5/3/2023 06:09:51

Sorry but I don't have more time today to look at your problem but please reply and might do tomorrow.
John_Ru (rep: 6142) May 4, '23 at 9:54 am
Thanks for the suggestion!! I uploaded a new version of the file along with the attached txt files within the "import text" tab. I also, have a comment highlighted in yellow in the same file, hopefully this whole thing is not confusing you. The numbers in bold (0.003 and 001) are not related to  the times in any way, but they would be used for other calculations. My only concern is about the times which is giving me a headache. I know I`m close to solve this but I don`t know what is it that I have to include!! 
I really appreciate your time and effort for helping me!
Isacri05 (rep: 2) May 4, '23 at 12:22 pm
Thanks for the revised file. Please see my revised answer.
John_Ru (rep: 6142) May 5, '23 at 12:05 pm
I'm sorry, I think I didnt explain myself better - my english is not the best. I guess my problem would be on the "extract time" sheet. As can see on my original excel file, I already imported the data using the macro on the second sheet, but when I want to copy the dates on the first sheet for cells A2:B12, the dates look different and they must be in the same format of hh:mm:ss AM/PM WITHOUT changing the original content (from the "import text" sheet). however, since each file has a different time and date format, I cannot get it to be the same when I manually cell format. It does work when i import it using legacy wizard from text, but it is annoying to do one by one. I also noticed the values from "times 2" file are not being recognized on your trial. Is there a reason why my "convert text numbers to numbers (from original excel file)" code wouldn`t work on your new code? 

I`m sorry for the inconvenience once again! 
Isacri05 (rep: 2) May 6, '23 at 8:14 am
Please see my revised answer but to be honest I think using my code would allow you to just copy cells from "Import text" to "extract time" without further effort.

Hope this works for you since I don't have more time to spend on this.
John_Ru (rep: 6142) May 6, '23 at 9:52 am
THANK YOU SO MUCH!!! The answer was so simple yet so difficult for me to figure it out! I really appreciate your help. You actually taught me new things that will definetly help me in future projects.
10 Star rating!
Isacri05 (rep: 2) May 6, '23 at 10:05 am
Glad that worked for you. Thanks for selecting my Answer.
John_Ru (rep: 6142) May 6, '23 at 10:07 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login