1

Very new to vba and I'm having some issues with a piece of code. In essence, I'm trying to perform different worksheet functions on user selected items from a list box in a user form.

Private Sub cmdRunStat_Click()
Dim averageValue As Single
Dim sdValue As Single
Dim maxValue As Variant
Dim minValue As Single
Dim modeValue As Single
Dim UserRange As String, sheetName As String


Set UserRange = ListBox1.Selected = True


If optAverage.Value = True Then

  averageValue = WorksheetFunction.Average(UserRange)
  MsgBox "The average of the selected data is " & averageValue

ElseIf optSD.Value = True Then

   sdValue = WorksheetFunction.StDev(UserRange)
   MsgBox "The standard deviation of the selected data is " & sdValue

ElseIf optMax.Value = True Then

   maxValue = WorksheetFunction.Max(UserRange)
   MsgBox "The maximum of the slected data is " & maxValue

ElseIf optMin.Value = True Then

   minValue = WorksheetFunction.Min(UserRange)
   MsgBox "The minimum of the slected data is " & minValue

Else

    modeValue = WorksheetFunction.Mode(UserRange)
    MsgBox "The mode of the slected data is " & modeValue

End If

End Sub
4
  • 1
    Are you sure the compiler error isn't "Object required" on the line Set UserRange = ListBox1.Selected = True? Commented Aug 4, 2016 at 16:22
  • you can't Set value to string . this is wrong Set UserRange = ListBox1.Selected = True Commented Aug 4, 2016 at 16:22
  • 1
    If you are using a ListBox to enter a string that represents a range, then you need to use Set UserRange = ListBox1.Value , just remember that string need to contain a format like Worksheets("Sheet1").Range("A1:D10") Commented Aug 4, 2016 at 16:50
  • Thanks for the input! Commented Aug 4, 2016 at 17:41

1 Answer 1

3

Set UserRange = ListBox1.Selected = True

That is an incorrect way to assign to a String Object.

If you are trying to get the selected value from the listbox then I think this is what you need?

Dim UserRange As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        UserRange = ListBox1.List(i)
        Exit For
    End If
Next i

And if it is a Range Object then you need to change the above as

Dim UserRange As Range

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        Set UserRange = ListBox1.List(i)
        Exit For
    End If
Next i
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the input! I'll make those changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.