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
Related
I wrote a macro that aims to open a workbook and split it into separate workbooks according to the names in a columns. I've done it many times with several macros but not this time.
The loop stops after creating correctly the first workbook because I get either a "run-time error -2147221080 (800401a8): Automation error" or "System Error &H800401A8 (-2147221080)".
I unsuccessfully looked for a solution in the internet all day long.
Here my code:
Sub Spacchettamento()
Application.ScreenUpdating = False
Dim FoglioMacro As Worksheet
Set FoglioMacro = ThisWorkbook.Sheets("Macro")
Dim FoglioParametri As Worksheet
Set FoglioParametri = ThisWorkbook.Sheets("Parametri")
Dim Percorsi As Worksheet
Set Percorsi = ThisWorkbook.Sheets("Percorsi")
Dim StatisticheFolderName As String
StatisticheFolderName = Percorsi.Range("A2").Value
Dim DialogBoxFileStatistiche As Office.FileDialog
Dim StatisticheFileName As String
Set DialogBoxFileStatistiche = Application.FileDialog(msoFileDialogFilePicker)
With DialogBoxFileStatistiche
.Filters.Clear
.Filters.Add "Excel Files", "*.xlsx?", 1
.Title = "Seleziona file Statistiche"
.AllowMultiSelect = False
.InitialFileName = StatisticheFolderName '
If .Show = True Then
StatisticheFileName = .SelectedItems(1)
End If
End With
Dim FileStatistiche As Workbook
Set FileStatistiche = Workbooks.Open(StatisticheFileName)
FileStatistiche.Activate
Dim FoglioTotale As Worksheet
Set FoglioTotale = Sheets(1)
FoglioTotale.Activate
Dim NuovoWorkbook As Workbook
Dim NuovoSheet As Worksheet
Dim PercorsoSalvataggio As String
PercorsoSalvataggio = FoglioParametri.Range("A9").Value
Dim NomeFileAsm As String
NomeFileAsm = FoglioParametri.Range("A13").Value
' here i want to create a list of names from the whole file and then start a loop
UltimaRiga = FoglioTotale.UsedRange.Rows(FoglioTotale.UsedRange.Rows.Count).Row 'find last row
FoglioTotale.AutoFilterMode = False
FoglioTotale.Range("E10:E" & UltimaRiga).Copy
FoglioParametri.Range("M1").PasteSpecial
FoglioParametri.Range("M1").RemoveDuplicates 1, xlYes
Dim i As Integer
For i = 2 To Application.CountA(FoglioParametri.Range("M:M"))
FoglioTotale.Range("A10:AO" & UltimaRiga).AutoFilter 5, FoglioParametri.Range("M" & i).Value
Set NuovoWorkbook = Workbooks.Add
Set NuovoSheet = NuovoWorkbook.Sheets(1)
ThisWorkbook.Activate
NuovoSheet.Name = "LENTI SK+STV"
FoglioTotale.Range("J1:W1").EntireColumn.Ungroup
FoglioTotale.Range("J1:W1").EntireColumn.Hidden = False
FoglioTotale.Range("AG1:AI1").EntireColumn.Hidden = False
UltimaRiga2 = FoglioTotale.UsedRange.Rows(FoglioTotale.UsedRange.Rows.Count).Row
FoglioTotale.Range("A1:AO" & UltimaRiga2).SpecialCells(xlCellTypeVisible).Copy
NuovoSheet.Range("A1").PasteSpecial xlPasteFormulas
FoglioTotale.ShowAllData
FoglioTotale.Range("A1:AO12").Copy
NuovoSheet.Range("A1:AO12").PasteSpecial xlPasteFormats
UltimaRiga3 = NuovoSheet.UsedRange.Rows(NuovoSheet.UsedRange.Rows.Count).Row
NuovoSheet.Range("A12:AO12").Copy
NuovoSheet.Range("A13:AO" & UltimaRiga3).PasteSpecial xlPasteFormats
NuovoSheet.Range("A10:AO" & UltimaRiga2).AutoFilter Field:=34, Criteria1:=""
NuovoSheet.ShowAllData
NuovoSheet.Range("A1:AO1").EntireColumn.AutoFit
NuovoSheet.Activate
ActiveWorkbook.Windows(1).DisplayGridlines = False
NuovoSheet.Range("AH1").EntireColumn.Hidden = True
NuovoSheet.Range("K1:V1").EntireColumn.Group
NuovoSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
NuovoWorkbook.SaveAs Filename:=PercorsoSalvataggio & NomeFileAsm & " - " & FoglioParametri.Range("M" & i).Value & ".xlsx"
NuovoWorkbook.Application.CutCopyMode = False
NuovoWorkbook.Close False
FoglioTotale.AutoFilterMode = False
Next i
FoglioParametri.Range("M1").EntireColumn.Delete
FileStatistiche.Application.CutCopyMode = False
FileStatistiche.Close savechanges:=False
MsgBox "Fatto!"
FoglioMacro.Activate
End Sub
Thank you all for your help and time
Luca
A guess, but you attempt
NuovoSheet.AutoFilterMode = False
after you've already closed the workbook:
NuovoWorkbook.Close False
Try moving the former line to before you save as / close.
I'm stuck. Try to add FreezePanes to all my excel files.
I have 28 folders "municipalities" in each folder 16 files: 1first, 2second,...
All filese Excel 2003 formats, and are divided into two types - with a figure in the title and without. Each file has several pages.
In parent directory i create file "base" in each two pages "municipalities" and "FilesList" and macro "Sub AddTo Freeze()"
Sub addToFreeze()
x% = firstDataBaseString
Do While Application.Workbooks(thisFileName).Worksheets("municipalities").Cells(x, 2) <> Empty
y% = firstDataBaseString
actMun$ = Application.Workbooks(thisFileName).Worksheets("municipalities").Cells(x, 2)
Do While Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1) <> Empty
actFile$ = TrimFormats(Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1)) & addedToMunicipal & ".xls"
openWaN$ = ThisWorkbook.Path & Application.PathSeparator & actMun & Application.PathSeparator & actFile
Dim fileHaveNum As Boolean
fileHaveNum = HasNumber(Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1))
If FileExists(openWaN) Then
Dim openApp As Excel.Application
Set openApp = New Excel.Application
openApp.DisplayAlerts = False
openApp.Visible = True
openApp.ScreenUpdating = False
Dim openBook As Workbook
Set openBook = openApp.Workbooks.Open(openWaN)
For Each ws In openBook.Worksheets
ws.Unprotect Password:="P$n177"
afName$ = TrimFormats(actFile)
sName$ = ws.Name
Workbooks(afName).Worksheets(sName).Activate
If fileHaveNum Then
Range("G4:G4").Select
ActiveWindow.FreezePanes = True
Else
Range("G6:G6").Select
ActiveWindow.FreezePanes = True
End If
ws.Protect Password:="P$n177"
Next
openBook.Close SaveChanges:=True
openApp.ScreenUpdating = True
openApp.Quit
End If
y = y + 1
Loop
x = x + 1
Loop
End Sub
Every tyme when i try run macro his say "Subscript out of range". Or add FreezePanese to my "base" file....
Solution:
Dont use
Dim openApp As Excel.Application
Set openApp = New Excel.Application
Dim openBook As Workbook
Set openBook = openApp.Workbooks.Open(openWaN)
Need use
Dim openBook As Workbook
Set openBook = Workbooks.Open(openWaN)
Workbooks(openBook.Name).Activate
I have a daily dump of 2 different text files (in the same folder) that get overwritten daily. I would like to be able to import them into an active spreadsheet with tab delimited, at the same time with a VBA code. I would really appreciate the help!
I am using excel 2016. My manual import method of 1 of the text file when recorded gives this code which is how i would like BOTH the text files to be imported (formatting preserved):
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Mr D\Music\New folder\B.txt", Destination:=Range("$A$1"))
.CommandType = 0
.Name = "B"
.FieldNames = True
.RowNumbers =enter code here False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 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
The code that i have tried using is from other similar questions posted here does not seem to work:
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\Mr D\Music\")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
do like this if your text files is with tab delimited.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
Dim sFolder As String, vDB, Ws As Worksheet
Dim rngT As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
sFolder = "C:\Users\Mr D\Music\"
Set folder = fso.GetFolder(sFolder)
' set the starting point to write the data to
Set Ws = ActiveSheet
'Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
Workbooks.Open Filename:=sFolder & file.Name, Format:=1
With ActiveWorkbook.ActiveSheet
vDB = .UsedRange
End With
ActiveWorkbook.Close
Set rngT = Ws.Range("a" & Rows.Count).End(xlUp)(2)
rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
Next file
Ws.Range("a1").EntireRow.Delete
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
From the second text file, the header will be ignored.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
Dim sFolder As String, vDB, Ws As Worksheet
Dim rngT As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
sFolder = "C:\Users\Mr D\Music\"
Set folder = fso.GetFolder(sFolder)
' set the starting point to write the data to
Set Ws = ActiveSheet
'Set cl = ActiveSheet.Cells(1, 1)
Ws.Cells.Clear
' Loop thru all files in the folder
For Each file In folder.Files
i = i + 1
Workbooks.Open Filename:=sFolder & file.Name, Format:=1
With ActiveWorkbook.ActiveSheet
If i = 1 Then
vDB = .UsedRange
Else
vDB = .UsedRange.Offset(1)
End If
End With
ActiveWorkbook.Close
Set rngT = Ws.Range("a" & Rows.Count).End(xlUp)(2)
rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
Next file
Ws.Range("a1").EntireRow.Delete
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
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
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