Having an optional parameter in a function - vb.net

Just a very quick question: I want to create a function with an optional parameter because I can't find a need for a parameter in the function. As a result I have coded the following function in visual basic:
Sub characterListLength(ByVal Optional)
Dim rowCount As Integer
Dim endOfArray As Boolean
While endOfArray = False
If dataArray(0, rowCount) And dataArray(1, rowCount) = "" Then
arrayLength = rowCount
endOfArray = True
Else
rowCount += 1
End If
End While
End Sub
However on the first line:
Sub characterListLength(ByVal Optional)
There is an error where an identifier is expected where the code says (ByVal Optional). I am not sure how to fix this error and have the optional parameter. If anyone could explain what else I need to do to fix it, that would be very useful.

You need an actual variable, something like:
Sub characterListLength(Optional ByVal optionalNumber As Integer = 0)

If you said:
because I can't find a need for a parameter in the function
Then use method without parameters:
Sub characterListLength()
'Here your code
End Sub

You need to give the parameter a name and switch the order of the keywords
Sub characterListLength(Optional ByVal p = Nothing)

A better "dot-nettier" alternative to optional parameters is to use overloaded methods. Consider following:
Overloads Sub ShowMessage()
ShowMessage("This is the default alter message")
End Sub
Overloads Sub ShowMessage(ByVal Message As String)
Console.WriteLine(Message)
End Sub
Written like this you can call the above method both ways:
ShowMessage() 'will display default message
ShowMessage("This is custom message") 'will display method from the parameter
Demo: http://dotnetfiddle.net/OOi26i

Related

MS-Access Modal Form instead of message box [duplicate]

I try to call a procedure giving to arguments, it throws a compile error stating "Expected: =".
...
Dim isWorkaround As Boolean
isWorkaround = False
If Check101.Value = True Then
isWorkaround = True
End If
...
'Procedure I try to call
ElseIf Combo_Report_Selection = "Adjusted Report" And Combo_someOther= "Other" Then
Call_01_Adj_Report(div, isWorkaround)
ElseIf Combo_Report_Selection = "Upload Log" Then
Call_03_Upload_Log
ElseIf Combo_Report_Selection = "Gather Summary" Then
Call_04_Adj_Summary
End If
Combo_Report_Selection.Value = Null
Combo_Statement.Value = Null
End Sub
__________________________________________
Private Sub Call_01_Adj_Report(ByRef calldiv As Long, ByRef isWorkaround As Boolean)
...
End Sub
__________________________________________
It fails when I insert the call " Call_01_Adj_Report(div, isWorkaround)".
It works when giving only one Parameter, but not for two. But in my understanding, the procedure call with arguments syntax is right. What might be the problem?
Your procedure call syntax is not right.
This: Call_01_Adj_Report(div, isWorkaround)
Needs to be: Call_01_Adj_Report div, isWorkaround
Or, with the obsolete explicit call syntax: Call Call_01_Adj_Report(div, isWorkaround)
I normally dislike explicit call syntax quite much, but here I like how it highlights how weird the procedure name is. Avoid underscores in public members (should be PascalCase), and start procedure names with a verb, e.g. CreateAdjustmentsReport:
CreateAdjustmentsReport div, isWorkaround
If you want to maintain parenthesis for calling a sub:
use Call keyword
Call Call_01_Adj_Report(div, isWorkaround)
Similarly if you declare a function that returns value (not sub), you can call the function with parenthesis without using "Call"
example:
Public Function func(ByVal variable As Integer)
variable = variable + 100
End Function
Public Sub test()
func (10)
End Sub

Compile Error "Expected: =" when calling another procedure

I try to call a procedure giving to arguments, it throws a compile error stating "Expected: =".
...
Dim isWorkaround As Boolean
isWorkaround = False
If Check101.Value = True Then
isWorkaround = True
End If
...
'Procedure I try to call
ElseIf Combo_Report_Selection = "Adjusted Report" And Combo_someOther= "Other" Then
Call_01_Adj_Report(div, isWorkaround)
ElseIf Combo_Report_Selection = "Upload Log" Then
Call_03_Upload_Log
ElseIf Combo_Report_Selection = "Gather Summary" Then
Call_04_Adj_Summary
End If
Combo_Report_Selection.Value = Null
Combo_Statement.Value = Null
End Sub
__________________________________________
Private Sub Call_01_Adj_Report(ByRef calldiv As Long, ByRef isWorkaround As Boolean)
...
End Sub
__________________________________________
It fails when I insert the call " Call_01_Adj_Report(div, isWorkaround)".
It works when giving only one Parameter, but not for two. But in my understanding, the procedure call with arguments syntax is right. What might be the problem?
Your procedure call syntax is not right.
This: Call_01_Adj_Report(div, isWorkaround)
Needs to be: Call_01_Adj_Report div, isWorkaround
Or, with the obsolete explicit call syntax: Call Call_01_Adj_Report(div, isWorkaround)
I normally dislike explicit call syntax quite much, but here I like how it highlights how weird the procedure name is. Avoid underscores in public members (should be PascalCase), and start procedure names with a verb, e.g. CreateAdjustmentsReport:
CreateAdjustmentsReport div, isWorkaround
If you want to maintain parenthesis for calling a sub:
use Call keyword
Call Call_01_Adj_Report(div, isWorkaround)
Similarly if you declare a function that returns value (not sub), you can call the function with parenthesis without using "Call"
example:
Public Function func(ByVal variable As Integer)
variable = variable + 100
End Function
Public Sub test()
func (10)
End Sub

Calling a function from a sub in VBA - qualifier error

I am trying to be more "object oriented" in my VBA code. However, I am having trouble passing variables through to functions. Here, I get an invalid qualifier error message on the IsEmpty function.
How can I correct my code?
Sub test_too_much_data()
If toomuchdata("Data input", "B1018") = False Then
MsgBox ("Sorry, the tool can only accomodate 1000 rows.")
Exit Sub
End If
End Sub
Function toomuchdata(sheet As String, range As Variant) As Boolean
toomuchdata = IsEmpty(Sheets("String")).range(range)
End Function
Thank you!
Update your Function code to something like below:
Function toomuchdata(sheetStr As String, RngStr As String) As Boolean
toomuchdata = IsEmpty(Sheets(sheetStr).Range(RngStr).Value)
End Function

Checking the passed variable

Is it possible to check if the passed variable in a function is a specific text? For example, I have a function:
Function dateCheck2(dateValue As String) As Boolean
If IIf(IsDate(frmResponse.txtEndDate), Format(CDate(frmResponse.txtEndDate), _
"mm\/dd\/yyyy"), "") = dateValue Then
dateCheck2 = True
Exit Function
End If
End Function
Then I have to call this in a UForm, lets say :
dateCheck2(sample)
What I want is to check if the passed variable is sample. Is there any way to do that?
Or you can create your own class (in VBA its called data type) which will hold variable name and values. Something like this
Public Type myFluffyType
fluffyName as string
fluffyValue as string
end Type
Then you can dim your variable like this
Dim fluffyVariable as myFluffyType
and initialize
fluffyVariable.fluffyName = "fluffyVariable"
fluffyVariable.fluffyValue = "notSoMuchFluffyValue"
and then when you passed it into your function you have all informations you need
Edit: on your problem you can do something like this. But im not sure what you exactly wana do next
Public type myType
varName as string
varValue as string
end type
Sub callDateCheck2
Dim sample as myType
sample.varName = "sample"
sample.varValue = "whateverValues"
Call dateCheck2(sample)
end sub
Function dateCheck2(dateValue As myType) As Boolean
if dateValue.varName = "sample" then
msgbox "everything ok"
else
msgbox "bad variable name"
end function
end if
If IIf(IsDate(frmResponse.txtEndDate), Format(CDate(frmResponse.txtEndDate), _
"mm\/dd\/yyyy"), "") = dateValue Then
dateCheck2 = True
Exit Function
End If
End Function

Optional Parameter without constants

I was wondering how I canspecify a Optional Parameter with a non-constant value?
Liek this for example:
Private Sub Foo(Optional ByVal Name as String = Application.ExecutablePath)
MsgBox("name: " & Name)
End Sub
is there a workarround?
So I can use a not constant value in the parameter as optional?
is there a workarround?
Yes:
Private Sub Foo(Optional ByVal Name As String = Nothing)
If Name Is Nothing Then
Name = Application.ExecutablePath
End If
MsgBox("name: " & Name)
End Sub
The most common way would be to avoid the Optional statement alltogether and use function overloading instead. This means you define a function with the same name multiple times with different declaration like so:
Private Sub Foo()
Foo(Application.ExecutablePath)
End Sub
Private Sub Foo(ByVal Name as String)
MsgBox("name: " & Name)
End Sub
That way, you can either supply a name or not when you call the function. The correct function is used depending on the declaration you use.
This approach seems more complicated, and in this simple case it probably is. However when your declaration gets more complicated, with more optional parameters in different orders mixed with non-optional parameters you will quickly learn to appreciate the possibilities of Overloading, I guarantee.
Expanding on Tim's correct answer
This code can be made more concise by using the If operator. This gives a one line setting of the alternate value if the parameter is Nothing
Private Sub Foo(Optional ByVal Name As String = Nothing)
Name = If(Name, Application.ExecutablePath)
MsgBox("name: " & Name)
End Sub
The If operator was introduced in 2010 IIRC so this code won't work in older versions of Visual Studio
You have to set it to an unused/reserved constant and then check for that in the method.
Private Sub(Optional ByVal Name as String = Nothing)
If Name Is Nothing Then Name = Application.ExecutablePath
MsgBox("name: " & Name)
End Sub
For some extra niceties, you can use xml comments and attributes to indicate via intellisense what the real "default" value is.