Variable required can't assign to this expression with parentheses - vba

I'm developing a macro with VBA and for some reason, I need to add parentheses to my variable when I call a function.
I do that to make my code cross-platform with the VBA on Mac and the data exchange with c++ libraries.
I have a sample of code which reproduces the error.
Private Type S0
x As Double
End Type
Private Type S1
s_0 As S0
End Type
Private Type S2
s_1() As S1
End Type
Private Sub RunMe()
Dim l As S2
ReDim l.s_1(1 To 2)
'no error
Call Display(l.s_1(1).s_0)
'compilation error : variable required can't assign to this expression
Call Display((l.s_1(1).s_0))
End Sub
Private Sub Display(d As S0)
MsgBox d.x
End Sub
As you can see, it's not logical to call my function Display with additionals parentheses but I don't know why, it's work like this for basic cases.
If I use only basic types, it works. I think it's related to the user define type.
So, I have two questions:
What is the VBA comportment when I add parentheses like in my example?
What can I do to avoid the compil error and keep the same comportment?
Thank you very much to read me and to help me!

The default variable passing method in VBA is ByRef. But "Even if a called procedure has declared its parameters as ByRef, you can force those to be ByVal by enclosing each argument within parentheses." see http://www.cpearson.com/excel/byrefbyval.aspx.
So your Call Display((l.s_1(1).s_0)) tries passing the (l.s_1(1).s_0) as user defined type S0 ByVal.
But User-defined type may not be passed ByVal. Thats why the error.

Related

Is it possible to work with return types of Windows API function calls in Visual Basic? 3 questions [duplicate]

I've not seen this in other languages but I see it a lot in VBA (which I just started working with). Suppose you have a table in Word and wish to set the rows to a certain height. If you do this
tbl.Rows.SetHeight InchesToPoints(1), wdRowHeightExactly
the table's rows indeed are set to 72 points or 1 inch in height. However, if you surround the arguments in parentheses, something I did instinctively, VBA gives an error -- expected:=.
I can solve this by using a throw-away variable, like this
x = tbl.Rows.SetHeight (InchesToPoints(1), wdRowHeightExactly)
or, of course, I can simply not surround the arguments in parentheses.
Microsoft's documentation on the SetHeight method doesn't mention any return value, but in any case, this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
My questions: What is this called? Should I use a throw-away variable or throw away the parentheses? What's the logic from Microsoft's point of view? Are there consequences to using one or the other, consequences I can't imagine (because they are unknown unknowns)?
Definitely don't introduce a "throw-away variable", especially if it's not declared, and especially if what you're invoking is a Sub, a procedure that doesn't return any value. Well you can, if you don't mind a compile-time error:
Expected Function or variable.
Now...
this behavior is extensive throughout VBA. It's not specific to the SetHeight method.
#Yoe3k put it nicely:
As for what it is called, I would guess "correct syntax" is the most appropriate word.
That's the whole answer: it's not about SetHeight, it's about how VBA's implicit procedure/member call syntax works. The explicit Call syntax has been obsolete since the wonderful advent of implicit calls, about a quarter of a century ago. So splattering Call keywords left & right and all over your code will, indeed, keep you the parentheses... if you hold them so dear.
But the "logic" of the implicit call syntax isn't all that complicated, really.
What follows is what I wrote on Documentation.SO about VBA and parentheses, hope it helps.
This is confusing. Why not just always use parentheses?
Parentheses are used to enclose the arguments of function calls. Using them for procedure calls can cause unexpected problems.
Because they can introduce bugs, both at run-time by passing a possibly unintended value to the procedure, and at compile-time by simply being invalid syntax.
Run-time
Redundant parentheses can introduce bugs. Given a procedure that takes an object reference as a parameter...
Sub DoSomething(ByRef target As Range)
End Sub
...and called with parentheses:
DoSomething (Application.ActiveCell) 'raises an error at runtime
This will raise an "Object Required" runtime error #424. Other errors are possible in other circumstances: here the Application.ActiveCell Range object reference is being evaluated and passed by value regardless of the procedure's signature specifying that target would be passed ByRef. The actual value passed ByVal to DoSomething in the above snippet, is Application.ActiveCell.Value.
Parentheses force VBA to evaluate the value of the bracketed expression, and pass the result ByVal to the called procedure. When the type of the evaluated result mismatches the procedure's expected type and cannot be implicitly converted, a runtime error is raised.
Compile-time
This code will fail to compile:
MsgBox ("Invalid Code!", vbCritical)
Because the expression ("Invalid Code!", vbCritical) cannot be evaluated to a value.
This would compile and work:
MsgBox ("Invalid Code!"), (vbCritical)
But would definitely look silly. Avoid redundant parentheses.
The most serious consequence of using parentheses inappropriately can best be demonstrated by code such as:
Sub Test()
Dim r As Range
Set r = Range("A1")
TestSub r
TestSub (r)
End Sub
Sub TestSub(parm As Range)
MsgBox parm.Address
End Sub
In that code TestSub r correctly passes a range object to TestSub. However, placing parentheses around the r, i.e. TestSub (r) causes VBA to evaluate r using its Value property and is therefore equivalent to TestSub r.Value. This then gives an error as it is passing a Variant (maybe a Variant/Double with a value of 123.45) to a subroutine that is expecting a Range.
It is basically just incorrect syntax to enclose parameters to a Subroutine within parentheses. They should only be used when a Function is returning a value.
P.S. I apologise that my example is Excel VBA. I hadn't noticed that the question was Word VBA, plus I could knock up an Excel example quicker than I could research Word VBA enough to give an example in it. The principle is the same in both though.

VBA - CallByName won't accept variant arguments

Solution: Just put brackets around Value in the CallByName statement to force evaluation of it.
Ex. CallByName MobClass, TargetData, vbLet, (Value)
Credit goes to Rory from the other post, which I will probably be deleting since it is no longer relevant and a possible duplicate.
I've spent a long time trying to figure out what was wrong with how I was using CallByName. I finally realized that its fourth argument (Args) will throw a type mismatch if the input is not either EXACTLY the same type as the input argument of what its calling or its hard-coded in.
(I don't even understand how, or why, it does this since VarType(Variant/Integer) = VarType(Integer))
So I either need a way to make it accept variant inputs or convert variables from Variant/Integer to Integer (or create a new variable) without a giant select case.
Edit: So my question wasn't clear so I'll explain it in more detail. I have a bunch of classes that I want to cycle through and call the Let property on. My simplified setup is:
Dim AllClasses as Collection
Sub SetAll(TargetProperty as String, Value as Variant)
For each ClassX in AllClasses
CallByName ClassX, TargetProperty, vbLet, Value
Next ClassX
End Sub
The problem is Value when it is initialized as Variant. The only time I can get it to not throw a type mismatch exception is when I initialize Value as the exact same type that the property wants, but I can't do that since the data types in the class vary.
Edit 2: I'm going to ask another question about the whole problem since no one seems to know much about CallByName
Edit 3: Here's a summary of what we have so far:
CallByName's fourth argument (Args) throws a type mismatch when trying to call the Let property on a class.
This only happens when the value trying to be assigned is stored in a Variant data type. It works perfectly if the variable is initialized to the same type the Let property is expecting OR if the value is hard-coded into the argument.
The Let property works fine on its own. It accepts Variant data types just fine.
My question is: Is there a way to stop this exception? I'm creating another post about other possible solutions to my overall problem.
The Problem is that you pass the properties-arguments by reference not by value, but you can't pass a reference to a different datatype (variant -> long) as the types don't match and it can't be converted as this would change the data type in the caller too. By using brackets, you force the argument to be passed by value and it can be casted as typeLong.
You can avoid this by using ByValin theProperty Letterinstead ofByRef(what is implicit used if not set). You are aware that by referencing a variable, changes made in the property change the callers value too?
Example:
Class PassExample
'Save as class module PassExample
Public Property Let PropByVal(ByVal NewVal As Long)
NewVal = 1
End Property
Public Property Let PropByRef(ByRef NewVal As Long)
NewVal = 1
End Property
Module with test sub:
'save as standard module
Sub test()
Dim v As Variant
v = 0
Dim ExampleInstance As New PassExample
CallByName ExampleInstance, "PropByVal", VbLet, v 'this works
CallByName ExampleInstance, "PropByRef", VbLet, v 'type mismatch
CallByName ExampleInstance, "PropByRef", VbLet, (v) 'this works as ByRef is changed to byval
Debug.Print v ' shows 0, not 1 as it should be if referenced
CallByName ExampleInstance, "PropByRef", VbLet, CVar(v) ' works too as it passes a function-result that can't be referenced
End Sub
Thanks to Rory and chris neilsen for providing the solution!

Subroutine will not compile

I'm using Access VBA, and I keep getting
Compile error: Argument not optional
whenever I try to pass a collection into a function. What is going on?
Private Sub btnTest_Click()
Dim GarbageLanguages As New Collection
GarbageLanguages.Add "VBA"
PrintCollectionCount (GarbageLanguages) '<-- error happens here
End Sub
Public Sub PrintCollectionCount(c As Collection)
Debug.Print c.Count
End Sub
Short Answer
Remove the parentheses from the following line:
PrintCollectionCount (GarbageLanguages)
Long Answer
For better or worse (mostly worse), VBA has both functions and subroutines:
Function - expression that must return a value
Subroutine - statement that cannot return a value
Unfortunately, using each of them requires slightly different syntax. Suprisingly, this is not a valid subroutine call:
Subroutine(arguments)
Instead, you need to use one of these two options:
Call Subroutine(arguments)
Subroutine arguments
It's even more unfortunate that when you use the wrong syntax, all you get is extremely cryptic error messages. Finally, it's also hard to get used to not using parenthesis because single arguments that are primitive types instead of objects actually work fine:
Subroutine(SomeString) ' works
Subroutine(SomeInteger) ' works
Subroutine(SomeObject) ' does not work
Subroutine(SomeString, SomeInteger) ' does not work
Aside from memorizing the awful error messages, you can try to train yourself to look out for whenever a space gets automatically inserted after the subroutine's name. This:
Subroutine(argument)
gets changed to this:
Subroutine (argument) '<-- RED FLAG

How do I pass a range obj variable to a sub in Excel VBA (2016) [duplicate]

This question already has an answer here:
Array argument must be ByRef
(1 answer)
Closed 6 years ago.
Given the following code:
I can not seem to successfully pass a Range Object Variable from one sub-function to another. I spent an entire day researching, and experimenting before I swallowed pride and came here.
Please read the comments below, and reply with any ideas you have regarding why the LAST two lines will not behave.
Public Sub doSomethingToRows(ROI As Range)
*'do Something with the cell values within the supplied range*
End Sub
'
Public Sub testDoAltRows()
Dim RegionOfInterest As Range 'is this an object or not?
'*The following yields: Class doesn't support Automation (Error 430)*
'*Set RegionOfInterest = New Worksheet 'this just gives an error*
Set RegionOfInterest = Worksheets("Sheet1").Range("A1")
RegionOfInterest.Value = 1234.56 '*okay, updates cell A1*
Set RegionOfInterest = Worksheets("Sheet1").Range("B5:D15")
RegionOfInterest.Columns(2).Value = "~~~~~~" '*okay*
'doSomethingToRows (RegionOfInterest) 'why do I get "OBJECT IS REQUIRED" error?
doSomethingToRows (Worksheets("Sheet1").Range("B5:C15")) 'but this executes okay
End Sub
From the msdn documentation of the Call keyword statement,
Remarks
You are not required to use the Call keyword when calling a procedure.
However, if you use the Call keyword to call a procedure that requires
arguments, argumentlist must be enclosed in parentheses. If you omit
the Call keyword, you also must omit the parentheses around
argumentlist. If you use either Call syntax to call any intrinsic or
user-defined function, the function's return value is discarded.
To pass a whole array to a procedure, use the array name followed by
empty parentheses.
From a practical standpoint, even though Subs can be called with or without the "Call" keyword, it makes sense to pick one way and stick with it as part of your coding style. I agree with Comintern - it is my opinion, based on observation of modern VBA code, that using the "Call" keyword should be considered deprecated. Instead, invoke Subs without parenthesis around the argument list.
And now the answer to the important question:
Why does your code throw an error?
Take for example the following Subroutine:
Public Sub ShowSum(arg1 As Long, arg2 As Long)
MsgBox arg1 + arg2
End Sub
We have established that, if not using the Call keyword, Subs must be invoked like so:
ShowSum 45, 37
What happens if it were instead called like ShowSum(45, 37)? Well, you wouldn't even be able to compile as VBA immediately complains "Expected =". This is because the VBA parser sees the parenthesis and decides that this must be a Function call, and it therefore expects you to be handling the return value with an "=" assignment statement.
What about a Sub with only one argument? For example:
Public Sub ShowNum(arg1 As Long)
MsgBox arg1
End Sub
The correct way to call this Sub is ShowNum 45. But what if you typed this into the VBA IDE: ShowNum(45)? As soon as you move the cursor off of the line, you'll notice that VBA adds a space between the Sub name and the opening parenthesis, giving you a crucial clue as to how the line of code is actually being interpreted:
ShowNum (45)
VBA is not treating those parenthesis as if they surrounded the argument list - it is instead treating them as grouping parenthesis. MOST of the time, this wouldn't matter, but it does in the case of Objects which have a default member.
To see the problem this causes, try running the following:
Dim v As Variant
Set v = Range("A1")
Set v = (Range("A1")) '<--- type mismatch here
Notice that you get a "Type Mismatch" on the marked line. Now add those two statements to the watch window and look at the "Type" column:
+-------------+-----+--------------+
| Expression |Value| Type |
+-------------+-----+--------------+
|Range("A1") | |Object/Range |
|(Range("A1"))| |Variant/String|
+-------------+-----+--------------+
When you surround an Object with grouping parenthesis, its default property is evaluated - in the case of the Range object, it is the Value property.
So it's really just a coincidence that VBA allowed you to get away with "putting parenthesis around the argumentlist" - really, VBA just interprets this as grouping parenthesis and evaluates the value accordingly. You can see by trying the same thing on a Sub with multiple parameters that it is invalid in VBA to invoke a Sub with parenthesis around the argument list.
#PaulG
Try this:
Public Sub Main()
Debug.Print TypeName(Range("A1"))
Debug.Print TypeName((Range("A1")))
End Sub
okay, I knew after I posted this question I'd be struck by lighting and receive an answer.
When passing an object VARIABLE to a sub-function and wishing to use parentheses "()", one must use CALL! Thus the correction to my code sample is:
**CALL doSomethingToRows(RegionOfInterest)**
Thank you!
Maybe we're talking about different things, but here's an example to make it a bit clearer what I mean.
Option Explicit
Sub TestDisplay()
Dim r As Range
'Create some range object
Set r = Range("A1")
'Invoke with Call.
Call DisplaySomething(r)
'Invoke without Call.
DisplaySomething r
End Sub
Sub DisplaySomething(ByVal Data As Range)
Debug.Print "Hi my type is " & TypeName(Data)
End Sub
Both calls work perfectly. One with Call and the other without.
Edit:
#Conintern. Thanks for explaining that. I see what is meant now.
However, I still respectively disagree.
If I declare the following:
Function DisplaySomething(ByVal Data As String)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
and invoke it:
Debug.print DisplaySomething(Range("A1"))
I believe that Excel has been clever and converted to a string. It can do that by invoking the Default Parameter and can convert to a string.
However, as in the original parameter example, If I declare the following:
Function DisplaySomething(ByVal Data As Range)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
There is no call on the Default Parameter, however it is called, because Excel was able to resolve it to that type.
Function DisplaySomething(ByVal Data As Double)
DisplaySomething = "Hi my type is " & TypeName(Data)
End Function
will return a double because it was able to coerce to a double.
Indeed in those examples the Default was called.
But in this example we are defining as Range. No Default called there however it is invoked - brackets or no brackets.
I believe this is more to do with Excel and data coercion.
Similar to the following:
Public Function Test(ByVal i As String) As Integer
Test = i
End Function
and invoking with:
Debug.print Test("1")
BTW, yes I know this isn't an object without a Default parmeter. Im pointing out data coercion. Excel does its best to resolve it.
Could be wrong mind you...

Why is it legal to pass "Me" ByRef in VB.NET?

I was shocked just a moment ago to discover that the following is legal (the C# equivalent is definitely not):
Class Assigner
''// Ignore this for now.
Public Field As Integer
''// This part is not so weird... take another instance ByRef,
''// assign it to a different instance -- stupid but whatever. '
Sub Assign(ByRef x As Assigner, ByVal y As Assigner)
x = y
End Sub
''// But... what's this?!?
Sub AssignNew()
''// Passing "Me" ByRef???
Assign(Me, New Assigner)
End Sub
''// This is just for testing.
Function GetField() As Integer
Return Me.Field
End Function
End Class
But what's even stranger just as strange to me is that it doesn't seem to do what I expect:
Dim a As New Assigner With {.Field = 10}
a.AssignNew()
Console.WriteLine(a.GetField())
The above outputs "10," not "0" like I thought it would (though naturally, this expectation was itself infused with a certain kind of horror). So it seems that you can pass Me ByRef, but the behavior is somehow overridden (?) by the compiler to be as if you had passed Me ByVal.
Why is it legal to pass Me ByRef? (Is there some backwards-compatibility explanation?)
Am I correct in saying that the behavior of doing this is overridden by the compiler? If not, what am I missing?
This behavior actually follows pretty directly from the Visual Basic specification.
11.4.3 Instance Expressions
An instance expression is the keyword Me, MyClass, or MyBase. An instance expression, which may only be used within the body of a non-shared method, constructor, or property accessor, is classified as a value.
9.2.5.2 Reference Parameters
If the type of the variable being passed to a reference parameter is not compatible with the reference parameter's type, or if a non-variable is passed as an argument to a reference parameter, a temporary variable may be allocated and passed to the reference parameter. The value being passed in will be copied into this temporary variable before the method is invoked and will be copied back to the original variable (if there is one) when the method returns.
(All emphasis mine)
So, the compiler will create a temporary variable assigned to the value of Me to be passed as the ByRef parameter. Upon return, no copy of the resulting value will take place since Me is not a variable.
It appears the compiler transforms "Me" into a variable which is then passed ByRef. If you compile your code, then open it with Reflector, you can see what's happening:
Class Assigner
''// Methods
Public Sub Assign(ByRef x As Assigner, ByVal y As Assigner)
x = y
End Sub
Public Sub AssignNew()
Dim VB$t_ref$S0 As Assigner = Me
Me.Assign((VB$t_ref$S0), New Assigner)
End Sub
Public Function GetField() As Integer
Return Me.Field
End Function
''// Fields
Public Field As Integer
End Class
So it looks like when you call AssignNew(), you are assigning the new instance to the internally generated variable. The "a" variable doesn't get touched because it's not even a part of the function.
This is just one of the thousands of possible 'almost errors' a programmer can make. MS caught most of them, in fact, sometimes I'm suprised at how many warnings do come up.
they missed this one.
As far as why it doesn't change 'me', it's a darn good thing! When you use 'me', it just passes a copy of the real class you are working with, for safety purposes. If this worked they way you were hoping, we would be talking GIANT side-effect. You're innocently working away with in your class' methods, and them BAM all of a sudden you are in an ENTIRELY different object! That would be awful! If you're going to do that, you might as well just write a piece of spagetti MS-Basic line-numbered code with all globals that get randomly set, and no subs/functions.
The way this works is the same way if you pass arguments in parenthesis. For example this works as expected:
Assign(Reference_I_Want_To_Set, New Assigner)
But this doesn't change anything:
Assign((Reference_I_Want_To_Set), New Assigner)
If you reflect the above type of code as adam101 suggests you will see similar results. While that is huge frustration with the parenthesis, it is a very good thing with Me !!!
what you need to do to make this code work is this:
Class Assigner
''// Ignore this for now.
Private newPropertyValue As Integer
Public Property NewProperty() As Integer
Get
Return newPropertyValue
End Get
Set(ByVal value As Integer)
newPropertyValue = value
End Set
End Property
''// This part is not so weird... take another instance ByRef,
''// assign it to a different instance -- stupid but whatever. '
Shared Sub Assign(ByRef x As Assigner, ByVal y As Assigner)
x = y
End Sub
''// But... what's this?!?
Shared Sub AssignNew(ByRef x As Assigner)
''// Passing "Me" ByRef???
Assign(x, New Assigner)
End Sub
End Class
then use it like
Dim a As New Assigner With {.NewProperty = 10}
Assigner.AssignNew(a)
my understanding is you cannot change the reference of the object while using it, so you need to change it in a shared sub
since Me cannot be the target of an assignment, the code seem to create a copy of it and from that point on, your not using the real object, but a copy of it