excel - passing a range object to a sub in VBA -


trying create subroutine takes range cell , calculates average of cells in column. error: object required

how can correct this?

    sub test()      dim rg range      set rg = thisworkbook.worksheets(1).range("b1")     columnaveragetotop (rg)      end sub      sub columnaveragetotop(rg range)     'calculates average of data in column , puts above data     cells(1, rg.column).end(xldown).offset(1, 0).value =  application.worksheetfunction.average(rg.columns(rg.column))     end sub 

good there's comment telling sub should do: read as: if run "test()", following happens: in passed range's column in row one, average of column's values should appear.

there 3 problems in code. first mentioned in previous comments: use either call columnaveragetotop(rg) or columnaveragetotop rg in test-routine. solution:

sub test()     dim rg range     set rg = thisworkbook.worksheets(1).range("b1")     columnaveragetotop rg end sub 

now succesfully enter columnaveragetotop routine, there's issue passing parameter worksheetfunction.average takes arguments documented here: https://msdn.microsoft.com/en-us/library/office/ff836809.aspx keep simple make sure pass range-object on calculation performed.

lastly, when using end , offset, make sure use them in right order. each of these functions provide new range object. see attempt cell below passed argument , go down , other values calculate average of range.

if truely need average of entire column, advise:

sub columnaveragetotop(rg range)     'calculates average of data in column , puts in row 1 of column     'we declare put value: cells(1,1) of column of range passed     'e.g. "b1" passed means average in "b1".     'same fore passing "b323"     rg.entirecolumn.cells(1, 1).value = worksheetfunction.average(rg.entirecolumn) end sub 

this include numerical value in row 1 of same column of passed range, though overwritten result. running same test multiple times therefore change result.

if need average of below 1st row until first blank row, should be:

.rg.entirecolumn.cells(1,1).value = worksheetfunction.average(rg.entirecolumn.range(cells(2, 1), cells(2,1).end(xldown)))

if need average of filled cells below referenced cell:

.rg.entirecolumn.cells(1, 1).value = worksheetfunction.average(rg.offset(1, 0).resize(rg.offset(1, 0).end(xldown).row - rg.offset(1, 0), 1))

hope helps out.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -