I was preparing a series of functions for Excel and am running into syntax issues. And as much as I am looking for information about it, I only find simple examples that do not answer my question.
Context
One of the functions copies a sheet several times giving each one a name within the loop.
' La función no es completa, es solo
' para que sirva de contexto en como
' intento usar la otra función en el if
'
Function CopySheets(Num As Integer)
Dim nameSheet As String
For i = 1 To Num
' Set del nombre de la hoja
nameSheet = "mes " & i
If SheetExist nameSheet Then
' si existe
Else
' si no existe
End If
Next i
End Function
The SheetExist function accepts as an argument a string with the name of the sheet and returns an True
or False
.
Problem
The problem I find is one of syntax, it is not a code that I am familiar with, and I have not found how to pass arguments inside a If
.
I have tried:
If SheetExist nameSheet Then
'...
If SheetExist(nameSheet) Then
'...
exist = SheetExist nameSheet
If exist Then
'...
And some more ways, all with wrong result.
Ask
What is the correct way to pass arguments to functions when they are part of a statement
If
?
Depends on the situation. This applies to both event procedures and functions.
Simple answer: if you're running a procedure/function only, you don't need the arguments in parentheses. But if you combine it with another order, command or similar, then it is mandatory to write the arguments in parentheses.
Let's take a simple example. I have this procedure defined in a module:
We execute it from another procedure:
If I run the above procedure, it runs without issue:
Now let's modify the Sub that we have called tests , as follows. Let's call the Sub Greeting with the Call command :
VBA editor gives error. Here we are required to separate the arguments of each command/procedure/function with parentheses. The correct way to write it would be like this:
That is, the VBA editor itself forces you to put the arguments of the Sub GREETING in parentheses, in order to read the code correctly.
The exact and technical reason why this is so I do not know. But I suppose it will be to be able to separate the arguments correctly from each command/procedure/function. That is, by enclosing the arguments of the Sub GREETING in parentheses , you allow VBA to read the code without errors or mistakes.
So, in answer to your question, the correct way to pass arguments to functions is:
You can go deeper into the subject in some links if you want. I'm sorry my answer is unprofessional, but I hope it can help a bit.