Excel VBA - Error Parsing Dates, Handling Strings - excel

The problem I have concerns a CSV file that I am seeking to parse into an excel spreadsheet.
An example of the data is as follows:-
01/02/2015,MXP,0.4,150.00,Producing design document, 64111258
02/06/2015,IHM,0.8,210.00,"Maximilian dolce, lorem ipsum", 64111258
02/06/2015,AXSP,0.6,250.00,"Magnificent, thanks very much", 64111258
Currently, this is the code I am using to parse the data:-
Sub OpenCSV()
Dim filePath As String
Dim intChoice As Integer
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
rowIndex = 0
If intChoice <> 0 Then
filePath = Application.FileDialog( _ msoFileDialogOpen).SelectedItems(1)
Open filePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItem = Split(LineFromFile, ",")
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 0).Value = LineItem(0) ' Date
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 1).Value = LineItem(1) ' Code
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 2).Value = LineItem(2) ' Hours
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 3).Value = LineItem(3) ' Cost
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 4).Value = LineItem(4) ' Description
rowIndex = rowIndex + 1
Loop
Close #1
End If
End Sub
The issues are as follows:-
Dates such as 02/06/2015 which are parsed and transposed to the excel cell will end up as 06/02/2015. This will not happen consistently, but happens randomly to various dates within the dataset.
CSV delimiter 4 will end up being parsed incorrectly where "" are in the data, as well as comma; Consequently the data is not transposed correctly to the relevant cell.
How can I go about correcting these errors?

Something like this should work for you:
Sub tgr()
Dim wb As Workbook
Dim wsDest As Worksheet
Dim sFilePath As String
Dim aData As Variant
sFilePath = Application.GetOpenFilename("CSV Files, *.csv", MultiSelect:=False)
If sFilePath = "False" Then Exit Sub 'Pressed cancel
Set wb = ActiveWorkbook
Set wsDest = wb.Sheets("Sheet2")
Application.ScreenUpdating = False
With Workbooks.Open(sFilePath)
aData = .Sheets(1).Range("A1", .Sheets(1).Cells(.Sheets(1).Rows.Count, "E").End(xlUp)).Value
.Close False
End With
Application.ScreenUpdating = True
With wsDest.Range("B11").Resize(UBound(aData, 1), UBound(aData, 2))
.Value = aData
.Resize(, 1).NumberFormat = "mm/dd/yyyy" 'Can set date format here, change to dd/mm/yyyy if needed
End With
End Sub

Most likely, the issue is a mismatch between the date format of your data and your Windows Regional Settings. Several ways to handle this
Change your Windows Regional Settings so they match
Change the file type to a *.txt file. Then use the Workbooks.OpenText method which allows you to specify the date column data type.
Create a Data Connection which will also allow you to do the same. Just be sure that you don't keep creating QueryTables. It the table is already there, either delete and recreate, or refresh.
Here is some code demonstrating the QueryTable method. In the Excel GUI this would be the Data ► Get External Data ► From text option
Option Explicit
Sub OpenCSV()
Dim filePath As String
Dim intChoice As Integer
Dim WS As Worksheet
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
filePath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
Set WS = Worksheets("sheet2")
With WS.QueryTables
'If it exists, either delete and re-import or refresh
If .Count > 0 Then
Range(.Item(1).Destination.Address).CurrentRegion.Delete
.Item(1).Delete
End If
End With
'
With WS.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=WS.Range("$B$11"))
.Name = "New Text Document"
.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
'make sure format argument matches format in the csv file
.TextFileColumnDataTypes = Array(xlDMYFormat)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
End Sub

Dim arr() As String
Dim newDate As Date
arr = Split(LineItem(0), "/")
newDate = DateSerial(Year:=arr(2), Month:=arr(1), Day:=arr(0))
Then use
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 0).Value = newDate

Related

Import CSV to new worksheet

I create a CSV BOM exported from CREO. I have a command button on my master worksheet, which will import the CSV to a new worksheet and name the worksheet with the CSV file name.
The issue is the import won't add the date to a new worksheet, instead it will open a new workbook.
Sub load_csv()
Dim fStr As String
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
'MsgBox "Cancel Selected"
Exit Sub
End If
'fStr is the file path and name of the file you selected.
fStr = .SelectedItems(1)
End With
Dim ws As Worksheet 'variable that will contain the new sheet
Dim help_name() As String 'helper string array that will contain the full path of your file
help_name = Split(fStr, "\") 'populating the variable with the full path, each '\' creates a new item
Set ws = ThisWorkbook.Sheets.Add 'adding a new sheet to your workbook
ws.Name = Replace(help_name(UBound(help_name)), ".bom", "", , , vbTextCompare) 'naming the new sheet with the name of the file and removing the '.bom'
'ubound returns the highest position of the array, which is always name of the file
With ThisWorkbook.Sheets("Sheet2").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=ThisWorkbook.Sheets("Sheet2").Range("$A$1"))
.Name = "CAPTURE"
.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, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
'ActiveWorkbook.Save
End With
End Sub
I created code to import the CSV to 'Sheet2' however I would like this added as a new worksheet and then that worksheet renamed to the file name without .BOM at the end.
I hope this helps :-)
if you paste it before the with statement and then replace the 'ThisWorkbook.Sheets("Sheet2")' with 'ws' in the with statement, I believe it should do what you need.
Dim ws As Worksheet 'variable that will contain the new sheet
Dim help_name() As String 'helper string array that will contain the full path of your file
help_name = Split(fstr, "\") 'populating the variable with the full path, each '\' creates a new item
Set ws = ThisWorkbook.Sheets.Add 'adding a new sheet to your workbook
'Original not reliable option 'ws.Name = Replace(help_name(UBound(help_name)), ".bom", "", , , vbTextCompare) 'naming the new sheet with the name of the file and removing the '.bom'
'ubound returns the highest position of the array, which is always name of the file
ws.Name = Left(help_name(UBound(help_name)), InStr(1, help_name(UBound(help_name)), ".bom", vbTextCompare) - 1) 'updated hopefully more reliable option of naming the sheet

Importing data from .csv to excel document using VBA

wondering if you can help out with a VBA issue. I pieced together the following without really knowing what I was doing:
Sub Import_Raw_Stripe_data()
Dim fileDialog As fileDialog
Dim strPathFile As String
Dim strFileName As String
Dim strPath As String
Dim dialogTitle As String
Dim Tworkbook As Workbook
Dim Sworkbook As Workbook
dialogueTitle = "Select File to Import"
Set fileDialogue = Application.fileDialog(msoFileDialogFilePicker)
With fileDialogue
.InitialFileName = "L:\Downloads"
.AllowMultiSelect = False
.Filters.Clear
.Title = dialogueTitle
If .Show = False Then
MsgBox "No file selected."
Exit Sub
End If
strPathFile = .SelectedItems(1)
End With
Set Sworkbook = Workbooks.Open(fileName:=strPathFile)
Set Tworkbook = ThisWorkbook
End Sub
Which, as far as I can tell opens a file dialog in excel, allows a user to choose a document and then opens it.
What I would like to do is the following:
1) Open a file dialogue and select a .csv file to import data from (complete?) into a .xlsm master file (with multiple sheets).
2) Select certain columns from the .csv (column A, Q, R and S in this case), copy them and import them into the second sheet of the master excel file entitled "Raw Stripe Data".
Any help in the matter would be greatly appreciated.
Update: I managed to find the following code:
Sub load_csv()
Dim fStr As String
With Application.fileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
'fStr is the file path and name of the file you selected.
fStr = .SelectedItems(1)
End With
With ThisWorkbook.Sheets("Stripe Raw Data").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=ThisWorkbook.Sheets("Stripe Raw Data").Range("$A$1"))
.Name = "CAPTURE"
.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, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
ActiveWorkbook.Save
End With
End Sub
This works great - but is there anyway to have it not override the data already imported? (for example, if i use it twice, the second import overrides the first).
ThisWorkbook.Sheets("Stripe Raw Data").Range("$A$1") specifies where the imported data is written to, that is the first cell of the sheet Stripe Raw Data.
Adapt this to your liking if you want the next import at another location.
As mentioned in the comments, you could change load_csv() to take the output destination as a parameter. If you also change it from Sub to Function, you can return the number of rows imported:
Function load_csv(rngDestination As Range) As Long
'...
With ThisWorkbook.Sheets("Stripe Raw Data").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=rng)
'...
.Refresh BackgroundQuery:=False
load_csv = .ResultRange.Rows.Count
'...
End Function
Now you can repeatedly call load_csv and provide it with the range where the output should begin for example:
Dim rngOutput As Range
Dim lngRows As Long
Set rngOutput = ThisWorkbook.Sheets("Stripe Raw Data").Range("$A$1")
lngRows = load_csv(rngOutput) ' load first file
lngRows = lngRows + load_csv(rngOutput.Offset(lngRows)) ' load second file
lngRows = lngRows + load_csv(rngOutput.Offset(lngRows)) ' load third file
lngRows = lngRows + load_csv(rngOutput.Offset(lngRows)) ' load fourth file
There is still much room for improvement:
Removing duplicate headers
Creating a loop instead of explicitly calling load_csv four times
Better control for the user to select files (multiselect)
Disconnecting the imported data from the QueryTable to reduce dependencies even after the import
Not importing in ThisWorkbook but afterwards saving ActiveWorkbook - they may not always be the same
...
But that's not part of this question. After all, all you wanted to know was:
is there anyway to have it not override the data already imported?
I hope I could sufficiently answer this with the above.

excel vba macro reading text files, one line in separate cell

Text file looks like below
a, John, "2014-2", ...
d, Will, "2016-7" , ...
I want to put element a in row 1, col 1, John in row 1 col 2, d in cell row 2, col 1, etc. Please help. Thanks. below are the code I have
Sub Importdata()
Open "C:\Users\apple\desktop\12345.txt" For Input As #1
r = 0
Do Until EOF(1)
Line Input #1, Data
ActiveCell.Offset(r, 0) = Data
r = r + 1
Loop
Close #1
End Sub
You can split each line using Split and , as delimiter
Try this it works fine:
Option Explicit
Sub Importdata()
Dim cet
Dim r As Long
Dim Data
Dim wk AS worksheet
Set wk = sheet1
Open "C:\Users\apple\desktop\12345.txt" For Input As #1
r = 1
Do Until EOF(1)
Line Input #1, Data
cet = Split(Data, ",")
if len(join(cet)) > 0 then
wk.Cells(r, 1) = cet(0)
wk.Cells(r, 2) = cet(1)
ENd if
r = r + 1
Loop
Close #1
End Sub
You could use the QueryTables property, importing and parsing the lines in one step. Easiest method is to do this using the Macro Recorder (Using the Data ► Get External Data ► From Text option from the Excel menu), then tweak to suit. In Excel, that would bring up the Text Import wizard, but you can also do it in VBA. Below is an example where I browse for the file, but you can easily hard-code it as you have in your original macro. Also note that I have explicitly declared the workbook and worksheets; you can easily change this if you wish.
EDIT Minor tweaks added for clarification
Option Explicit
Sub ImportData()
Dim sMyFile As Variant
Dim WS As Worksheet, WB As Workbook
Set WB = ThisWorkbook
Set WS = WB.Worksheets("sheet1")
sMyFile = Application.GetOpenFilename("Text Files(*.txt), *.txt")
If sMyFile <> False Then
With WS.QueryTables.Add(Connection:= _
"TEXT;" & sMyFile, _
Destination:=WS.Range("$A$1"))
.Name = "TestText"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlWindows
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
End Sub

Creating a new table in a new worksheet with maximum column values from other worksheets

Good evening, I am trying to load number of csv files and then calculate the max of each column from Column E to the last column (last column can be different for each run) and paste the values in a new work sheet.
I have tried to break my coading down in stages as I am learning VBA:
Step 1. Code to open folder select dialogue box and load each text files to excel in different worksheets with file name
Step 2. Code to open new worksheet and name as “Result”
with some sample data step 1 and 2 look like this [figure 1]:
and finally
Step 3. Code to find the maximum value for column E to last column and paste in the result sheet with the year number and the heigh number from the worksheet name, for example as follows:
So far with the help of this forum I have managed to create procedures with a simple userform with a run button that look like this:
I have manged to complete Step 1 and Step 2 (please see my codes below) but now really stuck with Step 3.
So far for step 3 I have managed to write something that can calculate max for column ‘E’ but just could not figure out how to calculate for all columns from column ‘E’ onwards for each work sheet and paste to the result sheet. I can calculate the col E max using the following code but the 5th line on the code do not copy to other columns:
Sub SumData()
Dim lastrow As Long
lastrow = Range("A1").End(xlDown).Row
Cells(lastrow + 2, "E").Formula = "=MAX(E2:E" & lastrow & ")"
Cells(lastrow + 2, "E").AutoFill , Type:=xlFillDefault
End Sub
I would really appreciate any advise with my step 3 and to make you understand easier I have copied my sample csv files in the following drop box link:
https://www.dropbox.com/sh/hqhzd901vwlgbl9/AAApxVc_CAsESxR9iZ4cHoOua?dl=0
The codes that I have created for step 1 and 2 are below and working for me:
Private Sub FilePath_Button_Click()
get_folder
End Sub
Private Sub Run_Button_Click()
load_file
End Sub
Public Sub get_folder()
Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
TextBox1.Text = FolderName
End Sub
Sub load_file()
Dim strFile As String
Dim WS As Worksheet
Dim test As String
Dim wb As Workbook
test = TextBox1.Text
strFile = Dir(Me.TextBox1.Text & "\*.plt")
Set wb = Workbooks.Add
'added workbook becomes the activeworkbook
With wb
Do While Len(strFile) > 0
Set WS = ActiveWorkbook.Sheets.Add
WS.Name = strFile
With WS.QueryTables.Add(Connection:= _
"TEXT;" & 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
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End With
Dim WS2 As Worksheet
Set WS2 = Sheets.Add
Sheets.Add.Name = "Result"
MsgBox "Job Complete"
End Sub
Private Sub UserForm_Click()
End Sub
There may lot simpler way of writing the codes but this is the best I could come up with for step 1 and 2. Many thanks in advance!
If all the worksheet names has the same format i.e XXX_XXX_XX_XXXX then it is pretty simple to extract those values. You can use Split function. here is an example
Sub Sample()
Dim sName(1 To 4) As String
Dim i As Long
sName(1) = "HP5_1gt_60_2010"
sName(2) = "HP5_1gt_70_2010"
sName(3) = "HP5_1gt_100_2008"
sName(4) = "HP5_1gt_110_2008"
For i = 1 To 4
Debug.Print "Height --> " & Split(sName(i), "_")(2)
Debug.Print "Year --> " & Split(sName(i), "_")(3)
Debug.Print "-----"
Next i
End Sub
Output
And to find the maximum value in a column, you can use the Max worksheet function in VBA. here is an example
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set rng = ws.Columns(5)
Debug.Print Application.WorksheetFunction.Max(rng)
End Sub
Output

Automatic Import (daily, csv & xls --> xls(m))

C
Dear SO-Community
i've got the following problem/challenge:
I need to automatically and daily import some data into one "master-xls". Both the source data and the consolidated data is organised in the same structure (plz have a look at the examples below)
Is it possibe, either way - with VBA (preferable) or without VBA - to automatically import data from the source files (file name is a combination of a string and the actual date) into the "destination-file"
Help and tips are very much appreciated! Plz point me into the right direction instead of presenting an already working example.
It is important, that the data from the new source file is appended to the data which is already existing!
best wishes,
Luke
source files:
*source 1
*source 2
master file
*master xls
I'm going to point you in the right direction, assuming I understand you correctly.
If you're opening up and wanting to read from an Excel spreadsheet, this will be useful:
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim cmd As ADODB.Command
'Set up the Connection to Excel
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0" 'or whatever your provider is
.ConnectionString = "Data Source="C:\My_source_file.xlsx';Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1';"
.Open
End With
'Set up the command to get all that mess out the spreadsheet.
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = cnn
.CommandText = "SELECT * FROM [WhateverSheetHasMyData$]"
End With
'Load up the recordset with everything in the worksheet.
Set rst = New ADODB.Recordset
With rst
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open cmd
End With
This should get you going in the direction you'd like to go. I am sure you can extrapolate from this how you might also use a command to deposit the data you've loaded into some other document, such as another spreadsheet or a database table.
Also, when it comes to appending the information, Excel has a nifty thing:
...
Dim ws As Excel.Worksheet
Dim lastrow As Integer
Set ws = wb.Sheets(1) 'wb being your workbook object; you could also use the sheet name instead of the index here
ws.Activate
lastrow = ws.Cells.SpecialCells(11).Row 'gets you the last row
So, you can use that lastrow+1 value as the starting point for your insert.
As an aside,
"Help and tips are very much appreciated! Plz do not bother to point me into the right direction..."
^ Generally not a good thing to say around these parts. Especially when you just said "I appreciate your help, but please don't bother helping me."
Have fun with this.
i've finally managed to automate the csv import.
some parts of the solution are originally found here:
http://software-solutions-online.com/2014/03/05/list-files-and-folders-in-a-directory/
below is my solution:
Sub listfiles_dir()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim lastrow As Integer
Dim lastcolumn As Integer
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim header As Boolean
header = True
Set wb = ActiveWorkbook
Set ws = wb.Sheets("raw")
ws.Activate
ws.Cells.ClearContents
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
'Set objFolder = objFSO.GetFolder(".\data")
Set objFolder = objFSO.GetFolder(ThisWorkbook.Path & "\data")
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file name
'Cells(i + 1, 1) = objFile.Name
'print file path
'Cells(i + 1, 2) = objFile.Path
i = i + 1
Debug.Print (objFile.Path)
If header = True Then
lastrow = 5
Else
lastrow = ws.Range("A" & Rows.Count).End(xlUp).row + 1 'gets you the last row
End If
Call import_csv(ws, objFile.Path, header, lastrow)
lastcolumn = ws.Range("$A$" & CStr(lastrow)).End(xlToRight).Column + 1
Cells(lastrow, lastcolumn) = objFile.Name
Debug.Print (lastcolumn)
If header = True Then
header = False
End If
Next objFile
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
'import files
Sub import_csv(sheet As Worksheet, fname As String, header As Boolean, row As Integer)
'
' importCSV Macro
'
Dim startingrow As Integer
startingrow = 1
If header = False Then
startingrow = 2
End If
Debug.Print ("$A$" & CStr(row))
With sheet.QueryTables.Add(Connection:= _
"TEXT;" & fname, Destination:=Range( _
"$A$" & CStr(row)))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
'.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
'.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFileStartRow = startingrow
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

Resources