Calculate average of selected cells in a column - vba

I'm trying to mark cells from a column then store the range into a variable. I would like to use the variable for another macro to calculate the average from the given range.
Sub UserRang()
Dim SelRange As Range
Set SelRange = Selection
Rng1 = SelRange.Address
MsgBox "You selected: " & Rng1
End Sub
Sub GradeAve()
GradeAverage = Application.WorksheetFunction.Average(Rng1)
MsgBox "The grade average is: " & GradeAverage
End Sub

Why can't you just use the AVERAGE worksheet function and skip the 'variable' in the middle?
ex. "=AVERAGE(A1:A5,A9,A12)"
VBA isn't great if you want to save and maintain static variables (or something resembling static variables).

Rng1needs to be declared on top of the module and should be a range not an address string as Averageneeds a range as argument.
Public Rng1 as Excel.Range
Sub UserRang()
Dim SelRange As Range
Set SelRange = Selection
Set Rng1 = SelRange
MsgBox "You selected: " & Rng1.Address
End Sub
Even better, use a function that returns the range instead of a sub.
Public Function GetUserSelection() as Excel.Range
Set GetUserSelection = Selection
End Function
Sub GradeAve()
GradeAverage = Application.WorksheetFunction.Average(GetUserSelection)
MsgBox "The grade average of " & GetUserSelection.Address & " is: " & GradeAverage
End Sub

Related

how to get user to input a range from a dialog box

so i need to get a range from the user, how is it possible to query the user to select a range, something like"
dim x as range
x = getrange("Select Range to Compare")
msgbox "The range selected is " & x
is there a way to do this?
You may try something like this. Tweak it as per your requirement.
Sub AskUserToSelectARangeToWorkWith()
Dim Rng As Range
On Error Resume Next
Set Rng = Application.InputBox("Select a Range to compare.", "Select A Range!", Type:=8)
If Rng Is Nothing Then
MsgBox "You didn't select a Range.", vbCritical, "No Range Selected!"
Exit Sub
End If
MsgBox "The Range selected is " & Rng.Address(0, 0)
End Sub

use inputbox as excel range

I'd like the user to input a range of cells such as A1:Z26. I've tried adding quotations, I've tried have 2 inputboxes, one for beginning and end of the range. But it errors out everytime with: 'method range of object_global failed'
I know it's a simple syntax issue (I think) so can anyone point me in the right direction in terms of how to have the user input a range that works in the set rng = range(msg)
Sub iterationLoop()
Dim rng As Range, iteration As Range
msg = "What is the range you'd like to look at: (e.g. A1:B2)"
InputBox (msg)
Set rng = Range(msg)
For Each iteration In rng
iteration.Select
If iteration = vbNullString Then
iteration = "add value"
MsgBox ("Cell: " & Selection.Address & " has no value")
End If
Next
End Sub
Application.InputBox allows you to specify the input type. Type 8 corresponds to a range. This will allow the user to either select the range with a mouse or type it in manually:
Sub test()
Dim rng As Range
Set rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the range you'd like to look at:", Type:=8)
MsgBox rng.Address
End Sub
If you intend your code to be used by others, you should probably wrap the Application.InputBox call in some error-handling code since the above code raises a run-time error if the user presses Cancel. Something like:
On Error Resume Next
Set rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the range you'd like to look at:", Type:=8)
If Err.Number > 0 Then
MsgBox "No Range Selected"
Exit Sub
End If
On Error GoTo 0
(though you might want to do something more useful than just quitting the sub)
aAdd
Dim rngstr as string
Then with the inputbox use this:
rngstr = inputbox(msg)
set rng = Range(rngstr)

Looping INDEX-MATCH VBA with Sub or Function not defined error

I have a looping INDEX-MATCH VBA that I am trying to debug, as it is constantly throwing a Sub or Function not defined error. With what I have already found on this site, I was able to check my references, but I still seem to be missing something ("Solver" is checked). At this point, an extra pair of eyes would be most helpful!
Private Sub Looping_Index_Match()
Application.ScreenUpdating = False
Dim rng As Range
Dim cell as range
Dim IndexRange as range
Dim MatchRange as range
Set rng = ActiveSheet.Range("D42:D241")
With Workbook("WorkCenter.xlsm").Sheets(ComboBox1.Value)
Set IndexRange=Range(.Range("M2"),.Range(“M2”).end(xlup))
Set MatchRange= Range(.Range("L2"),.Range(“L2”).end(xlup))
End With
For Each cell In rng
Cell.Offset(0,1)=Application.WorksheetFunction.Index(IndexRange,Application.WorksheetFuntion.Match(cell,Application.WorksheetFunction.Match(cell,MatchRange,0))
Next
Application.ScreenUpdating=True
End Sub
Notes: There are two workbooks involved. Data from the "Work Center" workbook column M is being retrieved and entered into the "Summary" workbook, as matched by serial numbers found in column L.
i will share a quick example i built:
i made a simple userform with 1 combobox and one command button. to the combobox i only added the name of the first sheet. the command button calls another macro stored in a separate module call Looping_Index, passing the combobox value
Private Sub CommandButton1_Click()
Call Looping_Index(UserForm1.ComboBox1.Value)
End Sub
Private Sub UserForm_Initialize()
ComboBox1.AddItem "Sheet1"
End Sub
Sub Looping_Index(hoja As String)
Sheets(hoja).Activate
Unload UserForm1
End Sub
this a simple example on how to work with userforms and passing values. hope it helps
Private Sub CommandButton1_Click()
Dim yoursheet As Worksheet
Dim yourworkbook As Workbook
Set yourworkbook = Workbooks("Book3.xlsx")
Set yoursheet = yourworkbook.Sheets(ComboBox1.Value)
With yoursheet
Set IndexRange = Range(.Range("M2"), .Range("M2").End(xlDown))
Set MatchRange = Range(.Range("L2"), .Range("L2").End(xlDown))
End With
ActiveWorkbook.ActiveSheet.Range("e42").Formula = "=index([" & yourworkbook.Name & "]" & yoursheet.Name & "!" & IndexRange.Address & ",match(d42" & ",[" & yourworkbook.Name & "]" & yoursheet.Name & "!" & MatchRange.Address & ",0))"
ActiveWorkbook.ActiveSheet.Range("e42:e241").FillDown
ActiveWorkbook.ActiveSheet.Range("e42:e241").Copy
ActiveWorkbook.ActiveSheet.Range("e42:e241").PasteSpecial xlValues
Application.CutCopyMode = False
Unload UserForm1
End Sub
Private Sub UserForm_Initialize()
ComboBox1.AddItem "Sheet2"
End Sub
This code below is working for me(same module):
Private Sub CommandButton1_Click()
Dim yoursheet As Worksheet
Set yoursheet = Sheets(ComboBox1.Value)
With yoursheet
Set IndexRange = Range(.Range("M2"), .Range("M2").End(xlDown))
Set MatchRange = Range(.Range("L2"), .Range("L2").End(xlDown))
End With
ActiveSheet.Range("e42").Formula = "=index(" & yoursheet.Name & "!" & IndexRange.Address & ",match(d42" & "," & yoursheet.Name & "!" & MatchRange.Address & ",0))"
ActiveSheet.Range("e42:e241").FillDown
Unload UserForm1
End Sub
Private Sub UserForm_Initialize()
ComboBox1.AddItem "Sheet2"
End Sub

excel VBA - return cell value that includes the escaping apostrophe

Given two cells with contents '=Foo and =Foo, getting the properties .Value,.Value2, .Text, .Formula all give me =Foo for both ranges.
How do I include the escaping apostrophe so that I get '=Foo when returning the cell value?
Use .PrefixCharacter to get the hidden apostrophe.
Like this: Debug.Print Range("A1").PrefixCharacter
Depending on what your trying to do with it, this Microsoft Post might be helpful.
Full Example:
Sub test()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
Dim rng As Range
Set rng = wks.Range("A1")
If Not rng.HasFormula Then
If rng.PrefixCharacter <> "" Then
MsgBox "Cell value is: " & rng.PrefixCharacter & rng.Text
Else
MsgBox "No prefix value in cell " & rng.Address
End If
End If
End Sub

VBA Syntax for properly formated output

I'm using the following vba originally provided by RBarryYoung. It's close but not quite there.
Sub quote()
' get the current selection
Dim rng As Range
Set rng = Selection
If rng Is Nothing Then
MsgBox "Nothing Selected", vbOKOnly, "Cannot Define Local Name"
Exit Sub
End If
' get the current worksheet
Dim wks As Worksheet
Set wks = rng.Worksheet
Sht = ActiveSheet.Name
xps = "!"
' get the name to define
Dim sNam As String
sNam = InputBox("Enter the Name to Define for this Sheet:", "Define Local Name")
If sNam = "" Then Exit Sub
' define a name local to this worksheet
wks.Names.Add sNam, Sht & rng.Address
End Sub
The issue is that the local "refer to" definition isn't properly formatted. It should be this
='VMware Servers'!$K$45
But the closest I've gotten is this:
="'VMware Servers'!$K$45"
And because of this, the value is off which breaks everything.