Set Range as Variable

smpatty08

Board Regular
Joined
May 16, 2014
Messages
155
I am trying to create a macro to enter a formula for the average of all the cells I have selected in the cell immediately below the selected range. I can not seem to find the correct syntax. Here is the code I have thus far.
Code:
Sub Test()Dim x As Range, y As Range


Set x = Selection


With Selection.Offset(Selection.Rows.Count).Resize(1, 1)
    .Select
End With


Set y = ActiveCell


y.FormulaR1C1 = "=Average(x)"


With Selection.Font
    .Bold = True
End With


End Sub
Any ideas on how to get this to work? Any help is appreciated!
 

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.
How about
Code:
Sub Test()
   Dim x As Range
   
   Set x = Selection
   
   With x.Offset(x.Rows.Count).Resize(1, 1)
       .FormulaR1C1 = "=Average(" & x.Address(, , xlR1C1) & ")"
       .Font.Bold = True
   End With
End Sub
 
Upvote 0
Do you really need a formula in the cell?
Why not have the script enter the results of the formula

Try this:
Code:
Sub My_Average()
'Modified  7/20/2018  3:42:55 PM  EDT
Dim ans As Long
ans = Application.WorksheetFunction.Average(Selection)
Selection.Offset(1).Value = ans
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,182
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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