1

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]:

enter image description here

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:

enter image description here

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:

enter image description here

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!

Community
  • 1
  • 1
Achak
  • 1,286
  • 2
  • 18
  • 36
  • I didn't understand what you want to do in Point 3. Can you explain it a bit further? – Siddharth Rout Nov 23 '14 at 07:30
  • Also to find the last row, you may want to see [this](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba) – Siddharth Rout Nov 23 '14 at 07:44
  • Hi Siddharth, basically in part 3 I am trying to find the largest value of each column from the 5th column (ignoring the first 4) for every wroksheet and paste in the result sheet. Now the triky bit is the part where the resultsheet will have 2 values from each worksheet name, for example first worksheet in figure 1 is 'HP5_1gt_70_2010.csv', so the result sheet need to take the year '2010' and the height value '70' and paste in the result sheet such a way that for each year the little max table look like figure 2. – Achak Nov 23 '14 at 08:15
  • Oh So where you have "max", you actually want a value there? not to mention create the headers as well as shown in row 1 and 9 from all the csv files. – Siddharth Rout Nov 23 '14 at 08:35
  • yes where I have 'max' I meant the largest value for each column from previous worksheets. and yes the headers are the one I mentioned that the tricky bit that I just can't think of logically how to extract the year and the height from the worksheet names. – Achak Nov 23 '14 at 08:55
  • I can tell you how to get the year and the height and also to find a maximum value in a column using examples. But then you will have to write your own code as this can be a very big project if I strat writing the code for everything. Do you think that would help? – Siddharth Rout Nov 23 '14 at 09:04
  • yes that would be a great help, thanks a lot – Achak Nov 23 '14 at 09:05
  • Kool. Gimme 10 mins. posting an answer. – Siddharth Rout Nov 23 '14 at 09:06

1 Answers1

1

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

enter image description here

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

enter image description here

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • thanks a lot, this is exactly the type of guidance I was looking for. I will work with this and try to build up. I will let you know how it goes. reagrds,Ayan – Achak Nov 23 '14 at 09:30
  • IF you don't mind could you just give me some idea of how I can drag the equation for the maximum value to the right till the last column? so that later I can just copy the entire rowm and take to resultsheet. – Achak Nov 23 '14 at 09:43
  • There are two ways to achieve what you want. `1` you can use the worksheetfunction in a loop to get max values in the columns. `2` You can find the lastrow in the worksheet using find as shown in [HERE](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba) and then put the max formula in that row for all the columns. In this case you can use `Cells(lastrow, ColNo).Formula = "=MAX(" & Split(Cells(, ColNo).Address, "$")(1) & "1:" & Split(Cells(, ColNo).Address, "$")(1) & lastrow - 1 & ")"` – Siddharth Rout Nov 23 '14 at 09:52
  • You would use this in a loop. Where `lastrow` is the row after the last row which has data and `ColNo` is the respective column number which I guess you want to start from `5` – Siddharth Rout Nov 23 '14 at 09:53
  • Brilliant, thank you so much! you really explained it well as I came across similar but just did not understand!Thanks again :) – Achak Nov 23 '14 at 10:00
  • So could you possibly mark @siddarth Rout@'s answer? – Mark Fitzgerald Nov 23 '14 at 10:06