I defined the following subroutine:
Sub EnterCellValueMonthNumber(cells As range, number As Integer) range(cells).Select ActiveCell.FormulaR1C1 = number End Sub
When I call the subroutine like this:
EnterCellValueMonthNumber ("N23:Q23",1)
I get the following error message:
Compile error Expected: =
I have no idea why I get this message. Does anyone know what I am missing?
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.
A statement in a Sub or Function procedure can pass values to called procedures by using named arguments. You can list named arguments in any order.
To call a form sub or function from a moduleThe form must be open before you make the call. To call an event procedure, you should call a public procedure within the form, and call the event procedure within this public procedure.
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.
You would call the sub as
EnterCellValueMonthNumber "N23:Q23", 1
No brackets. Or
Call EnterCellValueMonthNumber("N23:Q23", 1)
Brackets, and Call
before it.
Also, your Sub is expecting a Range object as the first argument and you're supplying a string; you should change the signature of the sub to:
Sub EnterCellValueMonthNumber(cells As String, number As Integer)
Also, I'm uncertain as to what you are trying to achieve with this code as it will only set the top-left cell of the range to 1. Would something like
Range(cells).Value = number ' Or, if you're going to be passing in something more complex later... Range(cells).FormulaR1C1 = number
be more appropriate?
I'd also be very wary of using Range("...")
without specifying which sheet you are referring to. This will act on whichever is the active sheet and can thus cause unexpected problems, almost always prefer SheetX.Range("...")
. Similarly for using .Select
, it's unnecessary, and can only cause problems for you in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With