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