0

I am trying to write a macro in VBA for excel that allows a user to input a range of cells. Then, I want the macro to sum up all of the cells, and input them into cell R32.

I have attached the code that I wrote for it so far. When I run the macro, I am allowed to select my range of cells.

However, I then receive the error message, run time error 1004- method range of object _Worksheet failed. This seems like something that could be a quick fix... But I am very stuck. Any help would be greatly appreciated.

Private Sub CommandButton5_Click()
    Dim userResponse As Range
    On Error Resume Next

    Set userResponse = Application.InputBox("select a range with the mouse",Default:=Selection.Address, Type:=8)
    On Error GoTo 0

    If userResponse Is Nothing Then
        MsgBox "Cancel clicked"
    Else
        MsgBox "You selected " & userResponse.Address
    End If

    Range("R32").Value = Application.WorksheetFunction.Sum(Range(userResponse))
End Sub
2
  • test comment, just to make sure this post didnt get deleted.. Commented Jun 24, 2015 at 15:25
  • 1
    Range("R32").Value = Application.WorksheetFunction.Sum(Range(userResponse)) will give you an error when userResponse is nothing. You need to put it inside the if statement testing for nothingness. Commented Jun 24, 2015 at 15:32

2 Answers 2

4

The problem here is that you are using Range(userResponse) for your Sum function.

The variable userResponse is already a Range, you don't need to specify it as one again.

Try this line of code and you will find it works as expected:

Range("R32").Value = Application.WorksheetFunction.Sum(userResponse)
Sign up to request clarification or add additional context in comments.

2 Comments

I upvoted this because I believe it's better than my answer. :-)
Thanks, this works as well! Gave it the green checkmark and upvote
2

What if you added .Address inside the Range() at the bottom, like so:

Range("R32").Value = Application.WorksheetFunction.Sum(Range(userResponse.Address))

Would that do what you're looking for?

2 Comments

Thought I tried that already, but just put it in and it works! Thank you, will give you the check mark once it lets me (5 min delay...)
@MaxH, I'd have you try Martin Parkin's solution instead, as mine contains redundant code (getting the address from the range and then the range from that address). His is cleaner!

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.