Merging text files in Excel 2013 - vba

New at Excel macros so need some help. I have about 60+ text files in a single directory each with just one column of data. I am trying to get/write a macro that will import all the text files but also add a second column that contains the file name.
I have the 2 steps I am trying to do. First Sub gets me the list of file names, the second sub gets my the content of the txt files. So the end result I am looking for is a single sheet with the txt content in column A and the source file's name in column B. I am struggling to get the file name in. The files imports must fallow below each other.
Dim xRow As Long
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\Desktop" '<<< Startup folder to begin searching from
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show
If .SelectedItems.Count <> 0 Then
xDirect$ = .SelectedItems(1) & "\"
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1)
xRow = xRow + 1
xFname$ = Dir
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & xFname$, Destination:=Range("$A$1"))
End With
Loop
End If
End With
End Sub
Sub TextContent()
Dim myfiles
Dim i As Integer
myfiles = Application.GetOpenFilename(filefilter:="Text Files (*.txt), *.txt", MultiSelect:=True)
If Not IsEmpty(myfiles) Then
For i = LBound(myfiles) To UBound(myfiles)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End (xlUp).Offset(1, 0))
.Name = "Sample"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.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 = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next i
Else
MsgBox "No File Selected"
End If
End Sub
Sub FileList()
Dim xRow As Long
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\Desktop" '<<< Startup folder to begin searching from
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show
If .SelectedItems.Count <> 0 Then
xDirect$ = .SelectedItems(1) & "\"
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1)
xRow = xRow + 1
xFname$ = Dir
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & xFname$, Destination:=Range("$A$1"))
End With
Loop
End If
End With
End Sub
Sub TextContent()
Dim myfiles
Dim i As Integer
myfiles = Application.GetOpenFilename(filefilter:="Text Files (*.txt), *.txt", MultiSelect:=True)
If Not IsEmpty(myfiles) Then
For i = LBound(myfiles) To UBound(myfiles)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End (xlUp).Offset(1, 0))
.Name = "Sample"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.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 = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next i
Else
MsgBox "No File Selected"
End If
End Sub

Something like this should do what you want.
Sub ImportTextFiles()
Dim myFile As String, text As String, textline As String
Dim iRow As Long
Application.ScreenUpdating = False
For iRow = 1 To Range("B" & Rows.Count).End(xlUp).Row
' Reset the text variable
text = ""
' Compose the full path
myFile = Range("A" & iRow).Value & "\" & Range("B" & iRow).Value
' Open the file
Open myFile For Input As #1
' Loop through the lines of the file
Do Until EOF(1)
' Read a line
Line Input #1, textline
' Concatenate text
text = text & " " & textline
Loop
' Close the file
Close #1
' Write text to cell
Range("C" & iRow).Value = Mid(text, 2)
Next iRow
Application.ScreenUpdating = True
End Sub
Feel free to modify the script to suit your specific needs. Keep in mind, you can do pretty much whatever you want to do...

Related

Set file origin when Importing text files to excel with VBA

I'm working with a VBA code to import TEXT files from a folder to excel workbooks.
My text file contains non-English encoding/origin and I want to import the file with 1253 Greek windows encoding but can't figure out how to add the origin:="1253" (if i'm right) in this code:
Sub LoadPipeDelimitedFiles()
'UpdatebyKutoolsforExcel20151214
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\*.txt")
Do While xFile <> ""
xCount = xCount + 1
Sheets(xCount).Select
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
& xStrPath & "\" & xFile, Destination:=Range("A1"))
.Name = "a" & xCount
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
xFile = Dir
End With
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no files txt", , "Kutools for Excel"
End Sub
I guess I was in a rush...
Here is the answer:
.TextFilePlatform = 1253

Getting Each Text Files Data Imported onto new row?

I am using the following code to scan a directory for text files.
It then imports all the data from each text file. At the moment my data is being imported scrambled with each word placed in a different row and column.
What I am wanting is each line of text per text file to be inserted into different columns in one row.
So text file 1 might contain:
A Cat
Mark Spence
Birmingham
And when imported into excel it should read:
A B C
A Cat Mark Spence Birmingham
then text file 2 would be inserted into the next row below.
so text file 2:
A Dog
David Gray
Manchester
Result:
A B C
A Cat Mark Spence Birmingham
A Dog David Gray Manchester
Please can someone show me where I am going wrong with this? Thanks
Sub Import_All_Text_Files_2007()
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
Dim strExtension As String
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Adds File Name as title on next row
Range("A1").Value = strExtension
'Sets Row Number for Data to Begin
nxt_row = Range("A1").End(xlUp).Offset(1, 0).Row
'Below is from a recorded macro importing a text file
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & strPath & strExtension, Destination:=Range("$A$" & nxt_row))
.Name = strExtension
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
'Delimiter Settings:
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileOtherDelimiter = "="
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strExtension = Dir
Loop
Application.ScreenUpdating = True
End Sub
Instead of QueryTables, use:
FileNum = FreeFile()
curCol = 1
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row,curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
I didn't test it, but it should at least guide you.

Excel macro to import text file and overwrite worksheet without breaking references

I have the following macro that I routinely use to import text files into separate excel worksheets:
Sub ImportManyTXTs()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt")
Do While strFile <> vbNullString
strFile2 = Replace(strFile, ".txt", "")
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "C:\location\of\folder\with\textfiles\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.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 = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileFixedColumnWidths = Array(7, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ws.Name = strFile2
strFile = Dir
Loop
End Sub
...but I would like to overwrite an existing worksheet if the same name is already used. In other worksheets I have references to cells in the worksheets that would be 'overwritten' so I need a way to do this without breaking the references to those cells. Anyone know of a good solution for this?
Assuming you don't have any other information stored on those sheets besides the querytable, try this (I cut out your with statement for space):
Sub ImportManyTXTs()
Dim strFile As String
Dim Sht As Worksheet
Dim ws As Worksheet
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt")
Do While strFile <> vbNullString
strFile2 = Replace(strFile, ".txt", "")
For Each Sht in Worksheets
If Sht.Name = strFile2 Then
Sht.Cells.ClearContents
Set ws = Sht
End If
Next Sht
If ws Is Nothing Then
Set ws = Sheets.Add
ws.Name = strFile2
End If
ws.Activate
With ActiveSheet.QueryTables.Add(Connection:= _
'YourStuffHere
End With
strFile = Dir
Loop
End Sub
In this case the contents of the sheet will just be replaced if it already exists, the references to the cells shouldn't change.

Leading zero in CSV on reopen [duplicate]

This question already has answers here:
Excel CSV - Number cell format
(16 answers)
Closed 9 years ago.
I have txt file which looks like below
I am importing the txt file in excel using the method shown here. Column Account is converted to text.
Once the data is imported, file looks like below.
I have a requirement to save the file as csv which is then imported by different system.
The problem is on reopen the csv file looks like below. The leading zero in account column disappears. I cannot add ' in front of Account column cells bcoz the system does not accepts. What can be done to preserve the leading zero on csv open/ reopen ?
I m doing this all using vba
Sub createcsv()
Dim fileName As String
Dim lastrow As Long
Dim wkb As Workbook
lastrow = Range("C" & Rows.Count).End(xlUp).Row
'If lastrow < 6 Then lastrow = 6
For i = lastrow To 3 Step -1
If Cells(i, 4).Text = vbNullString Then
Cells(i, 1).EntireRow.Delete
ElseIf Trim(Cells(i, 4).Value) = "-" Then
Cells(i, 1).EntireRow.Delete
ElseIf Cells(i, 4).Value = 0 Then
Cells(i, 1).EntireRow.Delete
ElseIf CDbl(Cells(i, 4).Text) = 0 Then
Cells(i, 1).EntireRow.Delete
End If
Next
lastrow = Range("C" & Rows.Count).End(xlUp).Row
'If lastrow < 6 Then lastrow = 6
retval = InputBox("Please enter journal Id", Default:="G")
Range("A3:A" & lastrow) = retval
retval = InputBox("Please enter Date", Default:=Date)
Range("B3:B" & lastrow) = retval
retval = InputBox("Please enter description", Default:="Master entry")
Range("E3:E" & lastrow) = retval
Dim strVal As String
strVal = InputBox("Please enter File Name", Default:="Data")
filePath = CreateFolder(strVal)
fileName = GetFileName(filePath)
ThisWorkbook.Sheets("Sheet1").Copy
Set wkb = ActiveWorkbook
Set sht = wkb.Sheets("sheet1")
Application.DisplayAlerts = False
wkb.SaveAs fileName:=filePath, FileFormat:=xlCSV
sht.Cells.Clear
importTxt wkb, filePath, fileName
sht.Columns("A:A").NumberFormat = "General"
sht.Columns("B:B").NumberFormat = "M/d/yyyy"
sht.Columns("D:D").NumberFormat = "0.00"
sht.Columns("E:E").NumberFormat = "General"
wkb.SaveAs fileName:=Replace(filePath, ".txt", ".csv"), FileFormat:=xlCSV
wkb.Close
Set wkb = Nothing
Application.DisplayAlerts = True
err_rout:
Application.EnableEvents = True
End Sub
Function CreateFolder(Optional strName As String = "Data") As String
Dim fso As Object, MyFolder As String
Set fso = CreateObject("Scripting.FileSystemObject")
MyFolder = ThisWorkbook.Path & "\Reports"
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
MyFolder = MyFolder & "\" & Format(Now(), "MMM_YYYY")
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
CreateFolder = MyFolder & "\" & strName & Format(Now(), "DD-MM-YY hh.mm.ss") & ".txt"
Set fso = Nothing
End Function
Sub importTxt(ByRef wkb As Workbook, ByVal txtLink As String, ByVal fileName As String)
With wkb.Sheets(fileName).QueryTables.Add(Connection:= _
"TEXT;" & txtLink, _
Destination:=Range("$A$2"))
.Name = fileName
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 2, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Function GetFileName(ByVal fullName As String, Optional pathSeparator As String = "\") As String
'?sheet1.GetFileName( "C:\Users\Santosh\Desktop\ssss.xlsx","\")
Dim i As Integer
Dim tempStr As String
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
tempStr = Right(fullName, iFNLenght - i)
GetFileName = Left(tempStr, Len(tempStr) - 4)
End Function
This is an unfortunate problem in MS Excel. I could not find any way around this, except to change the format and use xls. I was supplying data to my desktop application from a csv file that could be edited by anyone. Unfortunately, the leading zero problem stayed despite various things I tried. The only reliable method I found was to have a !before the number !00101 so that it was accepted as a string. This was okay for the application(it could replace the ! with nothing), but still the human readability factor was affected.
Depending on your application and use, you might have to use a different format.

Importing multiple CSV to multiple worksheet in a single workbook

How do I do this? Basically I want my multiple CSV files to be imported to multiple worksheet but in a single workbook only. Here's my VBA code that I want to loop. I need the loop to query all the CSV in C:\test\
Sub Macro()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\test\test1.csv", Destination:=Range("$A$1"))
.Name = "test1"
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
This guy absolutely nailed it. Very concise code and works perfectly for me on 2010. All credit goes to him (Jerry Beaucaire). I found it from a forum here.
Option Explicit
Sub ImportCSVs()
'Author: Jerry Beaucaire
'Date: 8/16/2010
'Summary: Import all CSV files from a folder into separate sheets
' named for the CSV filenames
'Update: 2/8/2013 Macro replaces existing sheets if they already exist in master workbook
Dim fPath As String
Dim fCSV As String
Dim wbCSV As Workbook
Dim wbMST As Workbook
Set wbMST = ThisWorkbook
fPath = "C:\test\" 'path to CSV files, include the final \
Application.ScreenUpdating = False 'speed up macro
Application.DisplayAlerts = False 'no error messages, take default answers
fCSV = Dir(fPath & "*.csv") 'start the CSV file listing
On Error Resume Next
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file
wbMST.Sheets(ActiveSheet.Name).Delete 'delete sheet if it exists
ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count) 'move new sheet into Mstr
Columns.Autofit 'clean up display
fCSV = Dir 'ready next CSV
Loop
Application.ScreenUpdating = True
Set wbCSV = Nothing
End Sub
Beware, this does not handles errors like you would have a duplicate sheet name if you imported a csv.
This uses early binding so you need to Reference Microsoft.Scripting.Runtime under Tools..References in the VBE
Dim fs As New FileSystemObject
Dim fo As Folder
Dim fi As File
Dim wb As Workbook
Dim ws As Worksheet
Dim sname As String
Sub loadall()
Set wb = ThisWorkbook
Set fo = fs.GetFolder("C:\TEMP\")
For Each fi In fo.Files
If UCase(Right(fi.name, 4)) = ".CSV" Then
sname = Replace(Replace(fi.name, ":", "_"), "\", "-")
Set ws = wb.Sheets.Add
ws.name = sname
Call yourRecordedLoaderModified(fi.Path, ws)
End If
Next
End Sub
Sub yourRecordedLoaderModified(what As String, where As Worksheet)
With ws.QueryTables.Add(Connection:= _
"TEXT;" & what, Destination:=Range("$A$1"))
.name = "test1"
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
You can use Dir to filter out and run with just the csv files
Sub MacroLoop()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("c:\test\*.csv")
Do While strFile <> vbNullString
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "C:\test\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub
I had 183 csv files to condense into one workbook, one worksheet per csv file to facilitate analysis of the data and did not want to manually do this one at a time. I tried the highest rated solution on this question but had the same problem as another user; the csv files would open, but nothing would be inserted to the target workbook. I spent some time and adjusted the code so that it works as in Excel 2016. I haven't tested on older versions. I have not coded in Visual Basic in ages so there's probably a ton of room for improvement in my code, but it worked for me in a pinch. In case anyone happens to stumble upon this question as I did, I'm pasting the code I used below.
Option Explicit
Sub ImportCSVs()
'Author: Jerry Beaucaire
'Date: 8/16/2010
'Summary: Import all CSV files from a folder into separate sheets
' named for the CSV filenames
'Update: 2/8/2013 Macro replaces existing sheets if they already exist in master workbook
'Update: base script as seen in: https://sites.google.com/a/madrocketscientist.com/jerrybeaucaires-excelassistant/merge-functions/csvs-to-sheets
'Update: adjusted code to work in Excel 2016
Dim fPath As String
Dim fCSV As String
Dim wbName As String
Dim wbCSV As Workbook
Dim wbMST As Workbook
wbName = "this is a string"
Set wbMST = ThisWorkbook
fPath = "C:\pathOfCSVFiles\" 'path to CSV files, include the final \
Application.ScreenUpdating = False 'speed up macro
Application.DisplayAlerts = False 'no error messages, take default answers
fCSV = Dir(fPath & "*.csv") 'start the CSV file listing
On Error Resume Next
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file
If wbName = "this is a string" Then 'this is to check if we are just starting out and target workbook only has default Sheet 1
wbCSV.Sheets.Copy After:=wbMST.Sheets(1) 'for first pass, can leave as is. if loading a large number of csv files and excel crashes midway, update this to the last csv that was loaded to the target workbook
Else
wbCSV.Sheets.Copy After:=wbMST.Sheets(wbName) 'if not first pass, then insert csv after last one
End If
fCSV = Dir 'ready next CSV
wbName = ActiveSheet.Name 'save name of csv loaded in this pass, to be used in the next pass
Loop
Application.ScreenUpdating = True
Set wbCSV = Nothing
End Sub
I didn't try this, but I'd go with this:
Dim NumFound As Long
With Application.FileSearch
.NewSearch
.LookIn = "C:\test\"
.FileName = "*.csv"
If .Execute() > 0 Then
For i = 1 To .FoundFiles.Count
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & "C:\test\" & (Application.FileSearch.FoundFiles(i)), Destination:=Range("$A$1"))
...
End With
Sheets.Add After:=Sheets(Sheets.Count)
Next i
End If
End With