Filter data based on a column and calculate average dynamically for all the filtered rows

sangria11

New Member
Joined
Oct 27, 2016
Messages
3
I have a table where I need to find the elements present in different samples.
For every sample, the no of iterations is a variable - I can have two rows of sample 1 and 3 rows of sample2 or 5 rows of sample4. the number of columns which are the elements can also be different. I have considered 3 samples and 17 elements in this case.


I need to filter based on the sample. All entries corresponding to sample1 needs to be copied to the next spreadsheet and the average needs to be calculated for the entire row of sample 1 , then sample 2 and so on


I am a beginner in vba and hence the code I used is not able to do it for dynamic range of values.


Also, I can only calculate the average using macro recorder. I am not aware how to combine these two codes into one. I tried to search a lot on this topic




I have included the expected results and my codes as well.


Any help would be much appreciated!!! Thank you

Table: (Data)

SampleEl1El2El3El4El5El6El7El8El9El10El11El12El13El14El15El16El17
Sample1393331150448175778441794312391313907730303037
Sample14120631438405767694454441478201298801580223333.09E+0873549450305027003906902154880002455497018558080745666911010050
Sample24288191371168673213947438529401216791373226402.95E+086984506027878150400033914100450221534401713619067524739827803
Sample24245631439610714724484447905601263631350216763.01E+086968038028027090355973114267580224788901681899069097269788499
Sample3442984141860866124457146818160103528940456483.16E+0875111780260889903618853145678202349342017066320751686311084680
Sample3438080143793969390480144814690104542863434913.2E+0875668430270340603533046151216402313697017178350741286011065210
Sample34367161381712645634671481304801069741237558913.59E+0881091740287259603533523158263802507659019268820846317612399330

<colgroup><col width="64" span="18" style="width:48pt"> </colgroup><tbody>
</tbody>




Expected Results :

Sample1393331150448175778441794312391313907730303037
Sample141206314384057676944544414782012988015802233330936000073549450305027003906902154880002455497018558080745666911010050
Average402697147144376273.54435.522074382126896.5148511170154680003.536774727152513501953453774400012277487927904037283365505029
Sample24288191371168673213947438529401216791373226402945300006984506027878150400033914100450221534401713619067524739827803
Sample24245631439610714724484447905601263631350216763013500006968038028027090355973114267580224788901681899069097269788499
Average426691140538969396.54215.5443217501240211361.5221582979400006976272027952620378003514184015223161651697759068311009808151
Sample34429841418608661244571468181601035289404564831634000075111780260889903618853145678202349342017066320751686311084680
Sample34380801437939693904801448146901045428634349132031000075668430270340603533046151216402313697017178350741286011065210
Sample343671613817126456346714813048010697412375589135942000081091740287259603533523158263802507659019268820846317612399330
Average439260141275366692.33468146587777105014.71013.33348343.33332023333.377290650272830033561807151719472390232717837830779763311516407

<colgroup><col span="9"><col><col span="8"></colgroup><tbody>
</tbody>


Code:
Sub sorttable()




    Dim j As Long 'row variable


    On Error GoTo Err_Execute


    Dim i As Long


'Start search in row 1 in sheet1
    j = 1


'Column counter for sheet2
   i = 1


  
   
 While Len(Range("A" & CStr(j)).Value) > 0


        If Range("A" & CStr(j)).Value = "Sample1" Then


            Range(Range("A" & CStr(j)), Range("A" & CStr(j)).End(xlToRight)).Select
            Selection.Copy
            Sheets("Sheet2").Select
            Sheet2.Cells(i, 1).Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
    ' Debug.Print Cells(j + 1, 1) = "=AVERAGE(A1:C" & j - 1 & ")"   ' This is the line i used to calculate average in between the cells, I guess it is wrong and it gives me error
            'Move counter to next Column
            i = i + 1
            'Go back to Sheet1 to continue searching
            Sheets("Sheet1").Select


        ElseIf Range("A" & CStr(j)).Value = "Sample2" Then


            Range(Range("A" & CStr(j)), Range("A" & CStr(j)).End(xlToRight)).Select
            Selection.Copy
                   Sheets("Sheet2").Select
            Sheet2.Cells(i, 1).Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
            'Move counter to next Column
           i = i + 1
           Sheets("Sheet1").Select




        ElseIf Range("A" & CStr(j)).Value = "Sample3" Then


            Range(Range("A" & CStr(j)), Range("A" & CStr(j)).End(xlToRight)).Select
            Selection.Copy
                  Sheets("Sheet2").Select
            Sheet2.Cells(i, 1).Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
            'Move counter to next Column
            i = i + 1
            'Go back to Sheet1 to continue searching
            Sheets("Sheet1").Select




        End If


            j = j + 1


      Wend


     
   Application.CutCopyMode = False


   MsgBox "the values have been extracted"


   Exit Sub


Err_Execute:
   MsgBox "Error Occured"


End Sub


[\code]

[code]

Sub test()
'
' Test Macro
' Using macro recorder
'


'
    Rows("1:1").Select
    Selection.Copy
    Sheets("Sheet2").Select
    Rows("1:1").Select
    ActiveSheet.Paste
    Range("A3").Select
    Sheets("Sheet1").Select
    Range("2:2,3:3").Select
    Range("A3").Activate
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet2").Select
    Rows("3:3").Select
    ActiveSheet.Paste
    Range("B5").Select
    Application.CutCopyMode = False
    Range("A5").Select
    Selection.Style = "Normal 2"
    ActiveCell.FormulaR1C1 = "Average"
    Range("B5").Select
    ActiveCell.FormulaR1C1 = "= AVERAGE(R[-2]C,R[-1]C)"
    Range("E7").Select
    ActiveWindow.SmallScroll Down:=2
    Range("B5").Select
    Selection.AutoFill Destination:=Range("B5:R5"), Type:=xlFillDefault
    Range("B5:R5").Select
    Range("A7").Select
    Sheets("Sheet1").Select
    Rows("4:5").Select
    Selection.Copy
    Sheets("Sheet2").Select
    ActiveSheet.Paste
    Range("A5").Select
    Columns("A:A").EntireColumn.AutoFit
    Application.CutCopyMode = False
    Selection.Copy
    Range("A9").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Selection.AutoFill Destination:=Range("A9:B9"), Type:=xlFillDefault
    Range("A9:B9").Select
    Range("B9").Select
    Selection.ClearContents
    ActiveCell.FormulaR1C1 = "= AVERAGE(R[-2]C,R[-1]C)"
    Range("B9").Select
    Selection.AutoFill Destination:=Range("B9:R9"), Type:=xlFillDefault
    Range("B9:R9").Select
    Range("A11").Select
    Sheets("Sheet2").Select
    Range("A27").Select
    Sheets("Sheet1").Select
    Range("A8:R10").Select
    Selection.Copy
    Sheets("Sheet2").Select
    Range("A11").Select
    ActiveSheet.Paste
    Range("A14").Select
    Application.CutCopyMode = False
    Selection.Style = "Normal 2"
    ActiveCell.FormulaR1C1 = "Average"
    Range("B14").Select
    ActiveCell.FormulaR1C1 = "= AVERAGE(R[-3]C:R[-1]C)"
    Range("B14").Select
    Selection.AutoFill Destination:=Range("B14:R14"), Type:=xlFillDefault
    Range("B14:R14").Select
    Range("A16").Select
End Sub


Sub copy_filtered_data()
' Worksheets("Results").Columns("A:Z").Delete Shift:=xlToLeft
On Error Resume Next
Worksheets("Sheet2").UsedRange.SpecialCells(xlCellTypeVisible).Copy _
Destination:=Worksheets("Results").Range("A1")
End Sub




Option Explicit
 
Sub Filter_Copy()
     
    Dim nextrow As Long
    Dim c As Range, rngCriteria As Range
     
    Worksheets.Add().Name = "Filtered_Data"
     
    Application.ScreenUpdating = False
     
    With Sheet3
        .AutoFilterMode = False
        Set rngCriteria = .Range("A1:A5")
        For Each c In rngCriteria
            nextrow = Worksheets("Filtered_Data").Cells(Rows.Count, "A").End(xlUp).Row
            .Range("A1:B" & .Cells(Rows.Count, "A").End(xlUp).Row).AutoFilter field:=1, Criteria1:="=" & c.Value
            .Range("A1:B" & .Cells(Rows.Count, "A").End(xlUp).Row).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy _
            Worksheets("Filtered_Data").Range("A" & nextrow + 1)
        Next c
    End With
     
    Application.CutCopyMode = False
    Application.ScreenUpdating = True
     
End Sub






Sub tester()
Dim lr As Long
Dim ws As Worksheet
Dim colno, i, j As Integer ' colno -- is the column on which the filter is present
Dim icol As Long
Dim arr As Variant
Dim header As String
Dim header_row As Integer
Dim rng As Variant


colno = 1
Set ws = Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, colno).End(xlUp).Row
header = "A1:Q1"
header_row = ws.Range(header).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
'    For i = 2 To lr
'        If ws.Cells(i, colno) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, colno), ws.Columns(icol), 0) = 0 Then
'        ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, colno)
'        End If
'    Next
arr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
'    ws.Columns(icol).Clear
   For i = 2 To lr
      ws.Range(header).AutoFilter field:=1
           ' Range(Range("A" & CStr(i)), Range("A" & CStr(i)).End(xlToRight)).Select
            'ws.Range("A1:C7").AdvancedFilter Action = xlFilterCopy, CriteriaRange = ws.Range("A1"), CopyToRange = Sheets("Sheet2").Range("A1"), Unique = False
           Debug.Print AutoFilter.Range.Copy
            Sheets("Sheet2").Select
            Sheet2.Cells(1, i).Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
            'Move counter to next Column
            i = i + 1
            ws.Select
    Next
  
            j = j + 1


        Application.CutCopyMode = False
   
        MsgBox "All matching data has been copied."
        ws.AutoFilterMode = False
        ws.Activate
End Sub




[\code]
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Sub filtercopy , copy_Filtered data and tester are not part of the codes i am using. I used it to test and unfortunately that got pasted as well
 
Upvote 0
this seems to be like built-in functionality, add subtotals. select a cell in data range and then ALT-D-B
(and ALT-D-B then ALT-R to remove)

can you use that?
if you need on a different sheet, just copy data then do subtotals
hth
 
Upvote 0

Forum statistics

Threads
1,214,642
Messages
6,120,701
Members
448,980
Latest member
CarlosWin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top