Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects as parameters in Excel VBA

Tags:

excel

vba

How do I pass an object to a private sub as a reference in Excel VBA? Below is what I am trying to do:

Sub main()
    Dim r As Range
    Set r = Sheets("Sheet1").Range(Cells(1, 1), Cells(27, 27))
    r.Select 'this works
    select_cells (r) 'this doesn't work
End Sub

Private Sub select_cells(a As Range)
    a.Select 'prompts Object Required error
End Sub
like image 540
Andrei Utkin Avatar asked Nov 21 '14 04:11

Andrei Utkin


People also ask

Does VBA pass object reference?

I rarely used ByRef in VBA since Objects are always passed by reference. The parameter just defines if the reference is passed by reference or by value more information here. The compile error should highlight a specific row.

How do you pass parameters in Excel VBA?

You can pass an argument by value if you include the ByVal keyword in the procedure's declaration. Arguments passed by value consume from 2–16 bytes within the procedure, depending on the argument's data type. Larger data types take slightly longer to pass by value than smaller ones.

How do you pass parameters in VBA subs?

VBA allows you to pass variables into subroutines and functions in two ways. You can specify either ByVal or ByRef for each of the variables that are passed in. The ByVal and ByRef distinction for subroutine and function parameters is very important to make. In VBA all objects are passed by reference.

What is passing object as argument?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.


1 Answers

select_cells (r) 'this doesn't work

You can't use parentheses to pass object parameters to a procedure. Just do this:

select_cells r

The archaic, obsolete Call keyword can be used, if you really want to keep the parentheses.

like image 98
Mathieu Guindon Avatar answered Sep 24 '22 03:09

Mathieu Guindon