Excel VBA - Import CSV without data connection - vba

I'm hoping to use this bit of connection style VBA code to import a number of CSV files. When I used the connection wizard, it downloads the CSV exactly in the table format I need it in etc, so I'm hoping to avoid doing a string reader...
Is there a way to do something like the following, but without creating a permanent connection?
Sub Macro1()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;T:\XYZ\KCross\Output\alpha.csv", Destination:=range("$B$2" _
))
.name = "alpha_1"
.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

I saw this on SO a few days ago . . .
' Merge data from multiple sheets into seperate sheets
Sub R_AnalysisMerger2()
Dim WSA As Worksheet
Dim bookList As Workbook
Dim SelectedFiles As Variant
Dim NFile As Long
Dim FileName As String
Dim Ws As Worksheet, vDB As Variant, rngT As Range
Dim vFn, myFn As String
Application.ScreenUpdating = False
SelectedFiles = Application.GetOpenFilename(filefilter:="Excel Files (*.csv*), *.csv*", MultiSelect:=True)
If IsEmpty(SelectedFiles) Then Exit Sub
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
FileName = SelectedFiles(NFile)
vFn = Split(FileName, "\")
myFn = vFn(UBound(vFn))
myFn = Replace(myFn, ".csv", "")
Set bookList = Workbooks.Open(FileName, Format:=2)
Set WSA = bookList.Sheets(1)
vDB = WSA.UsedRange
bookList.Close (0)
Set Ws = Sheets.Add(after:=Sheets(Sheets.Count))
ActiveSheet.Name = myFn
Ws.Range("a1").Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
Next
Application.ScreenUpdating = True
End Sub
' Merge data from multime files into one sheet.
Sub R_AnalysisMerger()
Dim WSA As Worksheet
Dim bookList As Workbook
Dim SelectedFiles() As Variant
Dim NFile As Long
Dim FileName As String
Dim Ws As Worksheet, vDB As Variant, rngT As Range
Application.ScreenUpdating = False
Set Ws = ThisWorkbook.Sheets(1)
Ws.UsedRange.Clear
'change folder path of excel files here
SelectedFiles = Application.GetOpenFilename(filefilter:="Excel Files (*.csv*), *.csv*", MultiSelect:=True)
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
FileName = SelectedFiles(NFile)
Set bookList = Workbooks.Open(FileName, Format:=2)
Set WSA = bookList.Sheets(1)
With WSA
vDB = .UsedRange
Set rngT = Ws.Range("a" & Rows.Count).End(xlUp)(2)
If rngT.Row = 2 Then Set rngT = Ws.Range("a1")
rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
bookList.Close (0)
End With
Next
Application.ScreenUpdating = True
Ws.Range("A1").Select
End Sub

It's not the most Object-Oriented solution (ideally we'd want to point at that specific connection by name or as an attribute of the QueryTable and delete it).
I noticed that when we create the Query Table the connection is added to the "Workbook.Connections" class as the last connection. This lets us take a count of the connections, pass it back to the connections class to point at this connection, then delete it.
This solution will only work if you want to delete the connection immediately with the creation of the Query Table. If you want to delete the connection at a later time for some reason, it looks like the connection name is derived from the csv workbook name, so you could always approach it that way too (ie pass the workbook name as an parameter to the connections class to reference it).
Assuming we want to delete immediately, the solution works like this:
Get the count of connections (ThisWorkbook.Connections.Count)
Pass it as an index parameter to the connections class (ThisWorkbook.Connections(ThisWorkbook.Connections.Count))
Call the .Delete method on the Connections class (ThisWorkbook.Connections(ThisWorkbook.Connections.Count).Delete)
Using your provided code, I'd add this line of code at the end of the sub like so:
Sub Macro1()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;T:\XYZ\KCross\Output\alpha.csv", Destination:=range("$B$2" _
))
.name = "alpha_1"
.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ThisWorkbook.Connections(ThisWorkbook.Connections.Count).Delete
End Sub
Another way to understand the solution would be writing it like this:
Dim wb as Workbook: set wb = ThisWorkbook
Dim conns as Connections: set conns = wb.Connections
conns(conns.Count).Delete
Note: I'm also assuming this macro will only operate on the workbook it lives in; I noticed your code uses the workbook pointer ActiveWorksheet so using ActiveWorkbook or whatever the workbook equivalent is might be more relevant in your use case.
Hope this helps!

Related

How can VBA read CSV with breakline inside double quote?

I'm trying to upload a CSV file with breaklines inside quotes (data.csv) but instead of putting all the text inside the quote in one cell, it still considers it as a new row.
When I open the CSV directly, everything works fine but when I run it through VBA, everything is getting messed up.
data.csv sample
cases,"variant:
option1: 0333102
option2: 1133202
option3: 4234442"
make-shift,"variant:
option1: shift iron
option2: workload
option3: network map
option4: lesson map"
Import_CSV Function
Function import_CSV(location As String, row As Integer, col As String) As Variant
Dim ws As Worksheet, strFile As String
Sheets("data").Visible = True
Sheets("data").UsedRange.ClearContents
Set ws = Sheets("data")
strFile = location
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
.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
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
import_CSV = Sheets("data").Range(col & "1:" & Get_C(Last_C(row, "data")) & Last_R(Get_C(Last_C(row, "data")), "data"))
Sheets("data").Visible = False
End Function
Assuming your import_CSV() returns the range in data worksheet with same size as the imported CSV, try below. Don't really need the row integer and col string, so I have omitted it.
Option Explicit
Function ImportCustomCSV(location As String) As Range
Dim oWbCSV As Workbook, oRngCSV As Range, oRngData As Range
ThisWorkbook.Worksheets("data").UsedRange.ClearContents
' Range to start pasting csv data
Set oRngData = ThisWorkbook.Worksheets("data").Range("A1")
' Assumes file availability is already checked
Set oWbCSV = Workbooks.Open(Filename:=location, ReadOnly:=True)
Set oRngCSV = oWbCSV.Worksheets(1).UsedRange
' Copy the CSV range to data worksheet
oRngCSV.Copy oRngData
' Make the data range the same rows and cols as imported csv
Set oRngData = oRngData.Resize(oRngCSV.Rows.Count, oRngCSV.Columns.Count)
' Cleanup
Set oRngCSV = Nothing
oWbCSV.Close SaveChanges:=False
Set oWbCSV = Nothing
' Return the updated data range
Set ImportCustomCSV = oRngData
End Function

Want to import bits (a couple of rows) of an .txt to excel

Hey so i found a specific query to import a file into excel from a specific row and delete the following datga each time you open it again. but is it also pssible to stop adding rows at a specific line? and is it possible to leave some rows out if there for example is a specific word in that line?
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.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 = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
You can do it, but not with a Querytable.
Try this code:
Private Sub Open_Click()
Dim fn As Variant, myLine As Long, txt As String, x As Variant, ouput As String
Dim i As Integer, j As Integer: j = 1
Dim sht As Worksheet
Set sht = Worksheets("Sheet1") 'Modify Sheet Name
fn = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
"Open File")
If fn = False Then Exit Sub
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(txt, vbNewLine)
For i = 0 To UBound(x)
If x(i) <> "SomeCriteria" Then 'Check for some criteria
sht.Cells(j, 1).Value = x(i)
j = j + 1
End If
Next i
End Sub
So what it does basically, it opens a user selected txt file and stores it in the variable txt. Do seperate the rows you can use the split-function. Now each line is stored in an array x. You could go trough the array/each line and take out the ones you want. To check if a specific word is in a line, use the InStr-function.

Excel Macro for Importing Text File with fixed width using VBA

Currently I'm using this code to import, delete and converting the text file to CSV file. And I'm doing all of this automatically while targeting the files location and the output location. The code is as the following:
Option Explicit
Sub DataConversion()
Dim directory As String, FileName As String, file As Object, i As Integer, j As Integer, fso As Object, c As Integer, MyFile As String, Content As String, textline As String, TextFileArray As Variant
Dim Path As String, TextFile As Integer, TotalFile As Integer, TFArray As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "C:\Users\Edward\Desktop\Extracted Data\Text File"
FileName = Dir(directory & "*.txt")
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.GetFolder(directory).Files
MyFile = "C:\Users\Edward\Desktop\Extracted Data\Text File\*.txt"
TextFileArray = GetFileList(MyFile)
TotalFile = file.Count
Select Case IsArray(TextFileArray)
Case True
For i = LBound(TextFileArray) To UBound(TextFileArray)
TFArray = TextFileArray(i)
TFArray = Replace(TFArray, ".txt", "")
ActiveSheet.Cells.ClearContents
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Edward\Desktop\Extracted Data\Text File\" + TextFileArray(i), _
Destination:=Range("$A$1"))
.Name = TFArray
.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 = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileFixedColumnWidths = Array(7, 22, 100, 14, 12, 11, 21, 20)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Rows("2:2").Select
Selection.Delete Shift:=xlUp
ActiveWorkbook.Save
ChDir "C:\Users\Edward\Desktop\Extracted Data\CSV File"
ActiveSheet.SaveAs FileName:= _
"C:\Users\Edward\Desktop\Extracted Data\CSV File\" + TFArray + ".csv", FileFormat:= _
xlCSV, CreateBackup:=False
Dim wb_connection As WorkbookConnection
For Each wb_connection In ActiveWorkbook.Connections
If InStr(TextFileArray(i), wb_connection.Name) > 0 Then
wb_connection.Delete
End If
Next wb_connection
Next i
Case False
MsgBox "No matching files"
End Select
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The Code runs fine but it displace the file by 1, example: File_1, File_2, File_3. When it calls the file it should target File_1 first and then only File_2 but instead of doing that the code is taking File_2 first and skipping File_1.
And the output is not as expected because the column width always change between each files and that causes the content to be split into different columns. The part where all the process happens I take from a previous macro that I have recorded.
Is there a way to make the column width change according to the text file? And how do I make the code to select the first file in the location instead of the second file?
Please help me.
EDIT: The width of the column for each file is unknown to me as there are about 300 plus files that I need to convert. However I found that there is a way to detect the width of the column using Transpose function. The code that found are as shown:
Dim WB As Workbook
Dim odWS As Worksheet
Dim fsuWS As Worksheet
Dim fd As FileDialog
Dim fcInt As Integer
Dim fcStr As String
Dim spAr As Variant
Dim dtAr As Variant
Set WB = ThisWorkbook
Set odWS = WB.Sheets.Add
odWS.Name = "OriginalData"
Set fsuWS = WB.Sheets("FieldSetUp")
'Transposing the range is essential for loading the values to the
'Array properties below
spAr = Application.Transpose(fsuWS.Range("SpanSpaces").Value)
dtAr = Application.Transpose(fsuWS.Range("ImpDataTypes").Value)
The part that interest me is the
spAr = Application.Transpose(fsuWS.Range("SpanSpaces").Value)
and
dtAr = Application.Transpose(fsuWS.Range("ImpDataTypes").Value)
as these are the parts that I need for me to make the macro to determine the width of the column. But I don't know what does "SpanSpaces" and "ImpDataTypes" do and what are their uses but I think it is just a Variant that have been declare earlier. Is there a way for me to change this two lines of code to make it fit my current one?
The whole code and post that I found this code can be found over here:
http://www.mrexcel.com/forum/excel-questions/676605-fill-array-property-range-variable.html

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.

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