Calling methods of a user-defined class without keyword "call" - excel

In the following code, tests 1,2 and 3 compile, but test 3 fails at run-time with "object doesn't support this property or method": ( why?)
Sub testdrive()
Dim sh As Worksheet
Dim val As Single
Dim myfoo As New CFoo
' test 1
val = 4
myfoo.sub1 (val)
' test 2
Set sh = ThisWorkbook.Sheets(1)
Call myfoo.sub2(sh)
' test 3
myfoo.sub2 (sh)
End Sub
The class module contains only the following:
Public f As Single
Public Sub sub2(sh As Worksheet)
End Sub
Public Sub sub1(s As Single)
End Sub
I cannot find a definitive statement of when I am obliged to use the "call" keyword.
Can anybody enlighten me?

When you parenthesize a parameter without using the keyword Call, in VBA syntax, this means that you want to force evaluating it then passing its Value. For VBA, the only way to achieve this is to evaluate the parameter then pass its value to the subroutine.
This works well if the parameter is a simple type, such as Single, so it works for Public Sub sub1(s As Single) then sub1(something) works fine.
BUT when the parameter is a worksheet, such as in Public Sub sub2(sh As Worksheet), when calling sub2(sh) with parenthesis, you are asking VBA to evaluate the worksheet, which it does not know how to achieve. Basically, Worksheet is not an object that VBA can evaluate. Therefore, it says
this object does not have this property or method
It means: the class Worksheet does not have a default property such as .Value, which on the other hand exists for a Range object, for example.
You cannot parenthesize the worksheet argument, unless you use the keyword Call, which prevents its prior evaluation.
Call myfoo.sub2(sh) '<~~ works fine
myfoo.sub2 sh '<~~ works fine
myfoo.sub2(sh) '<~~ problem, you are asking VBA to evaluate sh and pass its value
Finally, note that this has nothing to do with the fact that your Subs are class methods. It would have been the same if they were normal subroutines, placed in a normal code module.

Related

Using VBA in Excel - Static variable not retained when Multipage object has change event (changing pages)

I am having trouble with losing static variables within an Excel user form.
I have been working on a routine for excel. I am a (very) novice coder.
I am attempting to populate a cell range to an array. I have been able to do this without issue.
However, when I attempt to store the array as a *static * variable, the variable is not retained for as long as I want it to be.
I think the problem occurs when another page is selected in the multipage, the static variable is cleared.
Code is something like this:
Sub UserForm_Initialize ()
static myArray () as variant
dim myRange as range
set myRange = [namedrange]
myArray=myRange
msgbox myArray(0,0) 'this works fine
call OtherSub
end sub
sub OtherSub ()
msgbox myArray(0,0) 'this returns a blank
end sub
The first sub of code shows the array element just fine. The array element is blank in the second sub.
I have tried:
Declaring the array as a public variable, but this returns an error (I think that variables within user forms are private by default and cannot be changed).
using a very small variable (a simple string)
writing code in a module before opening the user form (variable is not retained).
I am aware that I can just write data to a cell range, but this would defeat the purpose. I was hoping to avoid multiple instances of reading large arrays from the worksheet.
This might explain it a bit clearer. Moving MyArray outside of the Procedure will set it's scope to a Module Level, making it usable through other subs within that module. You will generally want to keep the scope of your variables to the lowest level required. The other option would be to pass your variable as a parameter to your other procedure.
Option Explicit
Dim MyArray() As Variant ' Private Module Level Scope
Public ExampleVariable As String ' Public Module Level Scope (Not required, just showing an example.)
Sub UserForm_Initialize()
Dim myRange As Range ' Procedure Level Scope
Set myRange = [namedrange]
MyArray = myRange
MsgBox MyArray(0, 0) 'this works fine
Call OtherSub
End Sub
Sub OtherSub()
MsgBox MyArray(0, 0) 'this returns a blank
End Sub

Function vs Sub(ByRef)

About
This question is not about when to use a Function or a Sub, or the difference between ByRef and ByVal (although some insights will be unavoidable).
It is about scenarios which are 'commonly' solved with a Function, but can optionally be solved with a Sub using ByRef in the sense of 'modifying'.
The Code
Consider the following function:
' Returns the worksheet (object) with a specified name in a specified workbook (object).
Function getWsF(wb As Workbook, _
ByVal wsName As String) _
As Worksheet
' 'getWsF' is 'Nothing' by default.
' Try to define worksheet.
On Error Resume Next
Set getWsF = wb.Worksheets(wsName)
End Function
You can utilize it like the following:
' Writes the name of a specified worksheet, if it exists, to the `Immediate` window...
Sub testFunction()
Const wsName As String = "Sheet1"
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheet.
Dim ws As Worksheet
Set ws = getWsF(wb, wsName)
' Test if worksheet exists.
If Not ws Is Nothing Then
Debug.Print "The worksheet name is '" & ws.Name & "'."
Else
Debug.Print "Worksheet '" & wsName & "' doesn't exist in workbook '" _
& wb.Name & "'."
End If
End Sub
But you can also write each of the procedures in the following way:
' Although 'ByRef' is not necessary, I'm using it to indicate that whatever
' its variable is referring to in another procedure (in this case
' a worksheet object), is going to be modified (possibly written to
' for other datatypes).
Sub getWsS(ByRef Sheet As Worksheet, _
wb As Workbook, _
ByVal wsName As String)
' 'Sheet' could be 'Nothing' or an existing worksheet. You could omit
' the following line if you plan to use the procedure immediately
' after declaring the worksheet object, but I would consider it
' as too risky. Therefore:
' 'Reinitialize' worksheet variable.
Set Sheet = Nothing
' Try to define worksheet.
On Error Resume Next
Set Sheet = wb.Worksheets(wsName)
End Sub
' Writes the name of a specified worksheet, if it exists, to the `Immediate` window...
Sub testSub()
Const wsName As String = "Sheet1"
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheet.
Dim ws As Worksheet
getWsS ws, wb, wsName
' Test if worksheet exists.
If Not ws Is Nothing Then
Debug.Print "The worksheet name is '" & ws.Name & "'."
Else
Debug.Print "Worksheet '" & wsName & "' doesn't exist in workbook '" _
& wb.Name & "'."
End If
End Sub
Side by Side
Procedure
Function getWsF(wb As Workbook, _ Sub getWsS(ByRef Sheet As Worksheet, _
wsName As String) _ wb As Workbook, _
As Worksheet wsName As String)
Set Sheet = Nothing
On Error Resume Next On Error Resume Next
Set getWsF = wb.Worksheets(wsName) Set Sheet = wb.Worksheets(wsName)
End Function End Sub
Usage (relevant)
' Define worksheet. ' Define worksheet.
Dim ws As Worksheet Dim ws As Worksheet
Set ws = getWsF(wb, wsName) getWsS ws, wb, wsName
The Question(s)
Is the second solution viable?
I'm looking for a proper description of what each of the relevant two procedures do and some insights
in terms of common practice, readability, efficiency, pitfalls ...
In your case, I would use the Function approach and here are a few reasons:
I can use the result of the Function without storing the returning variable:
With getWsF(ThisWorkbook, "Sheet1")
'...
End With
Obviously, I would need to be sure it never returns Nothing or have some error handling in place.
or
DoSomething getWsF(ThisWorkbook, "Sheet1")
where DoSomething is a method expecting a Worksheet/Nothing
As #TimWilliams mentioned in the comments, if you don't expect multiple return values then this is the "expected" way to do it. A well-established convention is that if the method has no return value it should be a Sub. If it has a single return value then it should be a Function. If it returns multiple values then it should also be a Function and:
you either use a Class or Type to pack them as one result
or, the Function returns a primary value as the result and the rest of the return values ByRef (see #UnhandledException's answer for an example).
If you ever need to call the method with Application.Run then Function is safe. Using a Sub often leads to Automation Errors or code simply stops running after the method is executed. It doesn't matter if you need to use the result of the Function or not, don't call a Sub with Application.Run if you don't want nasty errors. Of course, to avoid issues with Application.Run, you could have a Function that doesn't get assigned a return value and still return the Worksheet ByRef but this would be too confusing for the reader.
Edit #1
Forgot to mention that the Application.Run automation errors are happening when calling methods from a different document (for Excel - different Workbook)
Edit #2
In this section I will try to address the proper description side of your question, without doing a begginer and an advanced explanation but a combined one.
Difference between a Sub and a Function
A Sub is just a function that does not return a value after the function executes. In lots of languages, such a function is called a Void Function.
The implications is that a Sub is just a stand-alone statement. It cannot be called from inside an expression. You can only call it with one of:
MySub [argsList]
Call MySub([argsList])
On the other hand, a Function can be used inside statements like:
arguments to other methods e.g. DoSomething MyFunction(...); Debug.Print MyFunction(...)
assignment e.g. x = MyFunction(...)
With blocks e.g. With MyFunction(...)
method chaining e.g. MyFunction(...).DoSomething
The convention mentioned above:
A well-established convention is that if the method has no return value it should be a Sub. If it has a single return value then it should be a Function
becomes quite clear when we understand that a Sub does something and a Function returns a single value, by definition.
Similarity between a Sub and a Function
Both value-returning functions (Function in VBA) and void functions (Sub in VBA) are receiving values as parameters. In VBA, it is possible to return results via ByRef parameters. Not all languages support ByRef parameters (e.g. Java - except modifying members of Objects for example).
Note that porting code from a platform that supports ByRef to another one that does not, can be quite time-consuming if the ByRef approach is abused in the source platform.
Difference between ByVal and ByRef parameters
Passing by value (ByVal):
a new memory space is allocated for a new variable which will be of local scope to the method being called
the contents of the original variable are copied in the newly allocated space of the new variable (for Objects the address of the interface Virtual Table is copied instead)
contents of the original variable are NOT changed regardless of what the method does
it is much safer because the programer does not need to keep in mind/care about other parts of the program (specifically the calling method)
Passing by reference (ByRef):
a new variable is created but no new memory space is allocated. Instead the new variable points to the memory space occupied by the original variable being passed from the calling method. Note that for Objects, the original variable is passed entirely (no new variable is created) unless the interface is different (passing a Collection as an Object type parameter - Object stands for IDispatch) but this is a discussion outside of the scope of this answer. Also note that if the parameter is declared as Variant, there are more complex operations happening to facilitate the redirection
the contents of the original variable can now be changed remotely because both the original variable and the newly created one point to the same memory space
it is considered more efficient because no new memory is allocated but this comes with the downside of increasing complexity
Comparison of the presented methods
Now that we have some understanding of the differences, we can look at both the presented methods. Let's start with the Sub:
Sub getWsS(ByRef Sheet As Worksheet, wb As Workbook, ByVal wsName As String)
Set Sheet = Nothing
On Error Resume Next
Set Sheet = wb.Worksheets(wsName)
End Sub
First of all, there should be an On Error GoTo 0 statement before the End Sub because otherwise the Error 9 is propagated up the calling chain (if sheet not found) and can affect logic inside other methods, long after the getWsS method has returned.
The method name starts with the verb "get" which implies that this method returns something but the method declaration is a Sub which is, by definition, more like a Do Something than a Return Something. Readability is certainly affected.
There is a need for an extra ByRef parameter to return the single piece of result. Implications:
it affects readability
it requires a declared variable inside the calling method
the result cannot he chained/used in other expressions within the calling method
it requries the extra line Set Sheet = Nothing to make sure the original variable does not retain previous contents
Now, let's look at the Function approach:
Function getWsF(wb As Workbook, ByVal wsName As String) As Worksheet
On Error Resume Next
Set getWsF = wb.Worksheets(wsName)
End Function
Same as before, there should be an On Error GoTo 0 statement before the End Function because otherwise the Error 9 is propagated up the calling chain. Also, the Workbook can be passed ByVal as best practice.
Obvious differences:
the name getSomething is perfect for a function that returns Something. Readability is far better than the Sub couterpart
the reader/maintainer of the code instantly knows that the function returns a Worksheet just by looking at the return type (as opposed to looking through a list of ByRef parameters and figuring out which one is the return variable)
the result can be chained/used in expressions
no extra lines of code are needed, the default returning value is already Nothing
the most widely accepted convention is used
I've used CTimer and it seems like on my x64 machine, the Sub approach runs faster with about 20ms when running the methods for a million times. Are these minor efficiency gains worth the loss in readability and flexibility of use? That is something that only the maintainer of the code base can decide.
To answer your question directly:
Q: Is it viable?
A: Yes, it will compile and carry out the functionality that you're expecting.
The grey area comes about when you ask should you do this.
There's definitely nothing stopping you (assuming you aren't subject to some company coding standards or anything). Typically however, functions are used to take in parameters, perform some kind of logic and return a value or object at the end of that logic.
Functions are typically non-destructive and don't change the values or properties of the input parameters. This becomes especially important for code readability and maintenance because other developers (and even yourself a few months from now) will read the code expecting functions to behave in a certain way.
Sub routines on the other hand are not expected to return anything, and so they are used to run concise, related sections of code that carry out some kind of logic relevant to the application. Going back to the point of readability and maintenance, it's reasonable to assume that objects and properties will change inside of a sub routine and so again this makes the developer's life a little easier.
Ultimately there's no hard and fast rules - but there are years of experience and best practice which are often good advice to take on in these scenarios :)
A good example for using both, a function and a ByRef parameter is a 'Try' function:
Public Function TryGetMyValue(ByRef outMyValue As Long) As Boolean
On Error Goto Catch
outMyValue = GetMyValue() 'Does anything to retrieve the value and could raise an error...
TryGetMyValue = True
Done:
Exit Function
Catch:
Resume Done
End Function
It could be used like that:
Public Sub TestTryGetMyValue()
Dim myValue As Long
If Not TryGetMyValue(myValue) Then Exit Sub
Debug.? "MyValue is: " & myValue
End Sub

Get Codename from property and pass as a variable

I have a function that takes a sheetname as a parameter like
Sub do_things(sheetCodeName as Variant)
sheetCodeName.Cells(1,1) = "Hello"
End Sub
I want to be able to get the codename of a given sheet using something like ActiveSheet.Codename and pass that as the codename parameter to my do_things subroutine. However, I get
Run-Time error '424' Object Required.
This seems to be because ActiveSheet.Codename is a string while actually typing the codename in the subroutine call passes it as a worksheet.
Is there a way for me to gather the codename of a sheet and pass it to my do_things sub without having to manually type it?
The simpler solution is just to pass a Worksheet object:
Sub do_things(ByVal ws As Worksheet)
ws.Cells(1,1).Value = "Hello"
End Sub
You can just pass the ActiveSheet directly if needed. Trying to use the .CodeName is unnecessary.
You could just pass the ActiveSheet, but if you can't do that for some reason you can change your sub:
Sub do_things(sheetCodeName as Variant)
Worksheets(sheetCodeName).Cells(1,1) = "Hello"
End Sub
It doesn't work now because the string is not an object.

Sub inside a UserForm can't receive Worksheet as parameter

for my internship I have to do some excel UserForms and vba macros.
I have a Private Sub inside my UserForm and i need to pass a WorkSheet as parameter to it. But i always get
"Execution error 438"
when the Sub is called.
What bothers me is that FirstBlankColumn works but FillAllBox doesn't.
I tried:
-putting FillAllBox in Public and neither Private nor Public
-turning FillAllBox into a Function
-changing the way i pass the Worksheet (ie: Set ws = Worksheets("ExportedData") then passingws)
'''vba
Private Function FirstBlankColumn(ws As Worksheet) As Long
'Yadda yadda does some stuff
'
'returns the number of the first blank column
End Function
Private Sub FillAllBox(ws As Worksheet)
' we never get to the FillBox calls
FillBox UserBox, ws
FillBox StockTransBox, ws
FillBox SemaineBox, ws
FillBox LocationBox, ws
FillBox ValeurBox, ws
End Sub
Private Sub UserForm_Initialize()
' displays correctly the number of the first blank column
MsgBox FirstBlankColumn(Worksheets("ExportedData"))
' Throws "error 438" upon call
FillAllBox (Worksheets("ExportedData"))
End Sub
'''
For a long time i passed the Sheet names and String to pass sheet as parameters. But having to call the sheet list in every function/sub to retrieve my sheet isn't optimised.
I'd like to be able to directly pass Sheets or Worksheets as parameter, reliably.
Thanks in advance.
This issue is your use of parentheses(()). Remove those from your call and you should be good to go.
Here is Microsoft's documentation on the use of parentheses.
Sub procedures, built-in statements, and some methods don't return a value, so the arguments aren't enclosed in parentheses
Function procedures, built-in functions, and some methods do return a value, but you can ignore it. If you ignore the return value, don't include parentheses. Call the function just as you would call a Sub procedure. Omit the parentheses, list any arguments, and don't assign the function to a variable.
FillAllBox Worksheets("ExportedData")

Difference between range and variable dim as range

I've built a class and need to record the data into a cell. Therefore I write a function doing this.
Codes below:
Option Explicit
Private sName As String
Public Property Let Name(ByVal strValue As String)
sName = strValue
End Property
Public Property Get Name() As String
Name = sName
End Property
Public Function ItemToCell(ByRef tgtCell As Range)
tgtCell = sName
End Function
And I also set a button to trigger this process:
Private Sub CommandButton1_Click()
Dim tmpData As New MyClass
tmpData.Name = "Tom"
Dim tgtCell As Range
Set tgtCell = Worksheets("Sheet1").Range("A1")
'Method 1, this failed with error 424
tmpData.ItemToCell (tgtCell)
'Method 2, it works
tmpData.ItemToCell (Worksheets("Sheet1").Range("B1"))
End Sub
I thought that these two methods were the same, but apparently they are not.
Why? Isn't the variable tgtCell an object?
Note that method 1A below, with the parentheses removed, DOES work as expected:
Public Sub CommandButton1_Click()
On Error GoTo EH
Dim tmpData As New MyClass
tmpData.Name = "Tom"
Dim tgtCell As Range
Set tgtCell = Worksheets("Sheet1").Range("A1")
'Method 1, this failed with error 424
tmpData.ItemToCell (tgtCell)
'Method 1A, this works
tmpData.ItemToCell tgtCell
'Method 2, it works
tmpData.ItemToCell (Worksheets("Sheet1").Range("B1"))
XT: Exit Sub
EH: MsgBox Err.Description, vbOKOnly, Err.Source
Resume Next
End Sub
The difficulty arises because the call to tmpData.ItemToCell requires an l-value (ie it is a ByRef argument) but the invocation statement IS NOT a function call, and so the parentheses are not the parentheses of invocation, but rather the parentheses of grouping. This can be a confusing issue in VBA.
The effect of the parentheses of grouping is to return the value of the variable tgtCell rather than its storage location, and implicitly evaluating the default member Value of the Range object. However, as you stumbled into with Method 2, there are circumstances where VBA does not implicitly evaluate the default member. Yes, it's confusing to everyone; don't feel alone.
One way to minimize the occurrence of this annoyance is to explicitly specify parameters for Functions and Subs (And Set/Let properties) as ByVal unless you actually desire to pass back a changed value to the caller. This wins by:
eliminating many instances of this annoying feature;
eliminating many subtle bugs when you treat the parameter as a local variable, and change its value expecting those changes to be local in scope, when they are actually non-local.
However, your circumstance is the rare one where this does not help. In these case it is imply best to not add parentheses to method calls until VBA complains of their absence, which is generally just for Functions rather than Subs and Property Setters/Letters.
In summary:
- Parameters should be explicitly specified as ByVal (rather than the default of ByRef) unless you really are passing back a calculated value (in which case a Function is a better implementation and usually sufficient) or when the language requires you to pass a ByRef argument.
- Parentheses should only be used in method invocations when VBA complains of their absence.

Resources