vba macro for importing latest text file using delimitors

RTLab

New Member
Joined
Mar 7, 2018
Messages
3
How do i combine these two modules so that i import the most recent .txt file using comma delimitor?


Code 1:
Sub GetMostRecentFile()

Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date

'set path for files - change for your folder
Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"

'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)


'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile

ImportTextFile FName:=myDir & strFilename, Sep:=Chr(9)

Set FileSys = Nothing
Set myFolder = Nothing
End Sub
Public Sub ImportTextFile(FName As String, Sep As String)
Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer
Application.ScreenUpdating = False
'On Error GoTo EndMacro:
SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row
Open FName For Input Access Read As #1
While Not EOF(1)
Line Input #1 , WholeLine
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
ColNdx = SaveColNdx
Pos = 1
NextPos = InStr(Pos, WholeLine, Sep)
While NextPos >= 1
TempVal = Mid(WholeLine, Pos, NextPos - Pos)
Cells(RowNdx, ColNdx).Value = TempVal
Pos = NextPos + 1
ColNdx = ColNdx + 1
NextPos = InStr(Pos, WholeLine, Sep)
Wend
RowNdx = RowNdx + 1
Wend
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
Close #1
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' END ImportTextFile
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub

Code 2:
Sub ImportData()
'
' ImportData Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files\I28183.txt", Destination:=Range("$A$1"))
.Name = "I28183"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
 

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
Code tags are your friend. Please see link in my sig.

GetMostRecentFile finds the most recent file and calls ImportTextFile to import it
I changed Chr(9) which is the tab character to "," in the calling line
ImportTextFile FName:=myDir & strFilename, Sep:="," 'Changed separator to comma

ImportData seems to be unused, but I changed
.TextFileSpaceDelimiter = False
to False
so a space would not be used as a delimiter

Code:
Option Explicit
Sub GetMostRecentFile()
    Dim FileSys As FileSystemObject
    Dim objFile As file
    Dim myFolder
    Dim strFilename As String
    Dim dteFile As Date
    
    'set path for files - change for your folder
    Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"
    
    'set up filesys objects
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)
    
    'loop through each file and get date last modified. If largest date then store Filename
    dteFile = DateSerial(1900, 1, 1)
    For Each objFile In myFolder.Files
       If objFile.DateLastModified > dteFile Then
           dteFile = objFile.DateLastModified
           strFilename = objFile.Name
       End If
    Next objFile
    
    ImportTextFile FName:=myDir & strFilename, Sep:="," 'Changed separator to comma
    
    Set FileSys = Nothing
    Set myFolder = Nothing
End Sub
Public Sub ImportTextFile(FName As String, Sep As String)
    Dim RowNdx As Long
    Dim ColNdx As Integer
    Dim TempVal As Variant
    Dim WholeLine As String
    Dim Pos As Integer
    Dim NextPos As Integer
    Dim SaveColNdx As Integer
    
    Application.ScreenUpdating = False
    'On Error GoTo EndMacro:
    SaveColNdx = ActiveCell.Column
    RowNdx = ActiveCell.Row
    Open FName For Input Access Read As [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] 
    While Not EOF(1)
        Line Input [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] , WholeLine
        If Right(WholeLine, 1) <> Sep Then
            WholeLine = WholeLine & Sep
        End If
        ColNdx = SaveColNdx
        Pos = 1
        NextPos = InStr(Pos, WholeLine, Sep)
        While NextPos >= 1
            TempVal = Mid(WholeLine, Pos, NextPos - Pos)
            Cells(RowNdx, ColNdx).Value = TempVal
            Pos = NextPos + 1
            ColNdx = ColNdx + 1
            NextPos = InStr(Pos, WholeLine, Sep)
        Wend
        RowNdx = RowNdx + 1
    Wend
EndMacro:
    On Error GoTo 0
    Application.ScreenUpdating = True
    Close [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] 
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' END ImportTextFile
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
 End Sub
 Code 2:
Sub ImportData()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files\I28183.txt", Destination:=Range("$A$1"))
        .Name = "I28183"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False     'Changed to False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub
 
Upvote 0
How do I combine these to macros so that when i import data from the most recent file, the data is imported using the importdata macro?

Rich (BB code):
Option Explicit
Sub GetMostRecentFile()
    
    Dim FileSys As FileSystemObject
    Dim objFile As File
    Dim myFolder
    Dim strFilename As String
    Dim dteFile As Date
        
    'set path for files - change for your folder
    Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"
    
    'set up filesys objects
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)
        
    
    'loop through each file and get date last modified. If largest date then store Filename
    dteFile = DateSerial(1900, 1, 1)
    For Each objFile In myFolder.Files
        If objFile.DateLastModified > dteFile Then
            dteFile = objFile.DateLastModified
            strFilename = objFile.Name
        End If
    Next objFile
       
    ImportTextFile FName:=myDir & strFilename, Sep:=","
    
    Set FileSys = Nothing
    Set myFolder = Nothing
End Sub
Public Sub ImportTextFile(FName As String, Sep As String)
Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer
Application.ScreenUpdating = False
'On Error GoTo EndMacro:
SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row
Open FName For Input Access Read As #1 
While Not EOF(1)
    Line Input #1 , WholeLine
    If Right(WholeLine, 1) <> Sep Then
        WholeLine = WholeLine & Sep
    End If
    ColNdx = SaveColNdx
    Pos = 1
    NextPos = InStr(Pos, WholeLine, Sep)
    While NextPos >= 1
        TempVal = Mid(WholeLine, Pos, NextPos - Pos)
        Cells(RowNdx, ColNdx).Value = TempVal
        Pos = NextPos + 1
        ColNdx = ColNdx + 1
        NextPos = InStr(Pos, WholeLine, Sep)
    Wend
    RowNdx = RowNdx + 1
Wend
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
Close #1 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' END ImportTextFile
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub
Rich (BB code):
Sub ImportData()
'
' ImportData Macro
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files\I28183.txt", Destination:=Range("$A$1"))
        .Name = "I28183"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

How do I combine these to macros so that when i import data from the most recent file, the data is imported using the importdata macro?
 
Upvote 0
This code will look for the most recent file in the coded directory (GetMostRecentFile) and open it (ImportData). The ImportTextFile sub is no longer used.

Code:
Option Explicit
Sub GetMostRecentFile()
    
    Dim FileSys As FileSystemObject
    Dim objFile As File
    Dim myFolder
    Dim strFilename As String
    Dim dteFile As Date
        
    'set path for files - change for your folder
    Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"
    
    'set up filesys objects
    Set FileSys = New FileSystemObject
    Set myFolder = FileSys.GetFolder(myDir)
        
    'loop through each file and get date last modified. If largest date then store Filename
    dteFile = DateSerial(1900, 1, 1)
    For Each objFile In myFolder.Files
        If objFile.DateLastModified > dteFile Then
            dteFile = objFile.DateLastModified
            strFilename = objFile.Name
        End If
    Next objFile
    
    ImportData myDir & strFilename
    'ImportTextFile FName:=myDir & strFilename, Sep:=","
    
    Set FileSys = Nothing
    Set myFolder = Nothing
    
End Sub
'Public Sub ImportTextFile(FName As String, Sep As String)
'
'    Dim RowNdx As Long
'    Dim ColNdx As Integer
'    Dim TempVal As Variant
'    Dim WholeLine As String
'    Dim Pos As Integer
'    Dim NextPos As Integer
'    Dim SaveColNdx As Integer
'    Application.ScreenUpdating = False
'    'On Error GoTo EndMacro:
'    SaveColNdx = ActiveCell.Column
'    RowNdx = ActiveCell.Row
'    Open FName For Input Access Read As [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] 
'    While Not EOF(1)
'        Line Input [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] , WholeLine
'        If Right(WholeLine, 1) <> Sep Then
'            WholeLine = WholeLine & Sep
'        End If
'        ColNdx = SaveColNdx
'        Pos = 1
'        NextPos = InStr(Pos, WholeLine, Sep)
'        While NextPos >= 1
'            TempVal = Mid(WholeLine, Pos, NextPos - Pos)
'            Cells(RowNdx, ColNdx).Value = TempVal
'            Pos = NextPos + 1
'            ColNdx = ColNdx + 1
'            NextPos = InStr(Pos, WholeLine, Sep)
'        Wend
'        RowNdx = RowNdx + 1
'    Wend
'EndMacro:
'    On Error GoTo 0
'    Application.ScreenUpdating = True
'    Close [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] 
'    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'    ' END ImportTextFile
'    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'End Sub
Sub ImportData(sFilePathNameExt As String)
'
' ImportData Macro
'
    Dim sFileName As String
    'C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files\I28183.txt
    
    sFileName = Mid(sFilePathNameExt, InStrRev(sFilePathNameExt, "") + 1)
    sFileName = Left(sFileName, InStr(sFileName, ".") - 1)
    
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & sFilePathNameExt, Destination:=Range("$A$1"))
        .Name = sFileName
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,227
Messages
6,170,848
Members
452,361
Latest member
d3ad3y3

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top