Quantcast
Channel: Active questions tagged row - Stack Overflow
Viewing all articles
Browse latest Browse all 447

Calculate average of both the columns and rows using VBA

$
0
0

I have a dataset that looks like the following:

enter image description here

Column A always contains ascending numbers (x-as in graphs for the time[s]).

The following columns contain data. Both the amount of rows and columns differs everytime dynamically.I want to do two things in Excel using vba:

  1. Calculate the average of each row and past it in the lastCol + 1 (GREEN)
  2. Calculate the average of each column and past in in the row áfter the lastRow of column A.

I am a bit struggling with the code (source). To make it work, but also to find the most efficient way.

'Option ExplicitPublic Sub ExtractInformation()'Calculate averages of columns      Dim lastCol As Long, lastRow As Long, m As Long, n As Long      Dim rng As Range'Find the last column.'Assumes the relevant column is the last one with data in row 5.'With Sheets("Graphs")      lastCol = Sheets("Graphs").Cells(1, Columns.Count).End(xlToLeft).Column      lastRow = Sheets("Graphs").Cells(Rows.Count, "A").End(xlUp).Row'End With'Iterate the columns from 1 (ie "A") to the last.      For m = 1 To lastCol          With Sheets("Graphs")'Define the data range for this column.'Assumes last cell from bottom of sheet is the end of data.              Set rng = .Range(.Cells(1, m), .Cells(.Rows.Count, m).End(xlUp))'Print the averages on row 125              .Cells(126, m) = WorksheetFunction.Average(rng) 'Print the averages on row 125          End With      Next'    For n = 1 To lastRow'        With Sheets("Graphs")''Define the data range for this column.''Assumes last cell from bottom of sheet is the end of data.''             Set rng = .Range(.Cells(n, 1), .Cells(n, .Columns.Count).End(xlLeft))''Print the averages on row 125'          .Cells(128, n) = WorksheetFunction.Average(rng) 'Print the averages on row 125'      End With'  NextEnd Sub

This code works somewhat, except for the part with the comments (uncommenting gives "Error 1004". Also, the calculated averages do not match the averages that I calculated manually. I assume that has something to do with the different amount of rows for each column.


Viewing all articles
Browse latest Browse all 447

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>