0

I want to create a subroutine that accepts a range as an argument. Something like this:

Sub Test(dataRange As Range)

    Sheet2.Range("A1").Cells.value = dataRange.Cells(1, 1)

End Sub

However when I try to select the range on Excel and run it, I get a "Reference is not valid" error.

Note: I am trying to run this by going into the Developer tab and clicking on the "Macros" button. In there I type in Test($A$2:$B$4), and then I get the error.

Is there a way to call a custom VBA subroutine from an Excel spreadsheet and pass arguments to it?

Thanks

3
  • 1
    It's really surprising that you can see Subs with argument list in your macro list... Commented Jun 3, 2014 at 15:51
  • @CST-Link you can't. I think OP is trying to simply manually type in the sub name & arguments. Commented Jun 3, 2014 at 15:54
  • 2
    You simply can't pass a Range object like that. Commented Jun 3, 2014 at 16:12

2 Answers 2

2

Although this is not a generalized answer, it should work for your purposes:

Sub Test(Optional dataRange As Range = Nothing)
    If dataRange is Nothing then Set dataRange = Range(Selection.Address)
    Sheet2.Range("A1").Cells.value = dataRange.Cells(1, 1)

End Sub

From the macro menu, simply type in Test and hit the "Run" button.

This will use the current Selection as the data range.

Alternatively, use an InputBox to capture the range argument:

Sub Test2()
    Dim dataRange as Range
    Set dataRange = Application.InputBox("Select range", Type:=8)
    If dataRange is Nothing then Exit Sub
    Sheet2.Range("A1").Cells.value = dataRange.Cells(1, 1)

End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I went with the second option. It was just what I was looking for. Thanks for your answer!
0

You would need quotes around the range:

Test(Range("$A$2:$B$4"))

Comments

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.