Home » excel » excel – How to use a Range variable as subroutine argument

excel – How to use a Range variable as subroutine argument

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a very basic question about VBA sub routines. What I’m trying to do is

  1. Set activeCell to Range variable
  2. Pass that variable to Sub routine
  3. Do something with the activeCell

What I tried to do is

Sub myMacro()

    Dim myCell As Range

    Set myCell = ActiveCell

    mySub(myCell)

End Sub

Sub mySub(cell As Range)
    ' Do something
End Sub

I keep getting an “Object required” error.
What is the problem here?

How to&Answers:

When you pass arguments to a function, you dont need to use parenthesis. Eg:

     mySub myCell

You could also use Lance sugention and use use Call AND parenthesis. (Press F1 over Call in the VBA Editor to get more info about it)

     Call mySub(myCell)

Either way is correct, but the first notation might prove more helpful while learning VBA as the great mojority of Answers in forums use the first one.

Answer:

You need to use the Call statement on the subroutine.

Call mySub(myCell)