Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function or Public Sub ? 2

Status
Not open for further replies.

timhans

Programmer
Jun 24, 2009
75
I cobbled together my first function two days ago(with help from the form)

Function ClearAll(c As String, f As Form)
Dim ctl As Control
For Each ctl In f.Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox, acListBox, acCheckBox
If ctl.ControlSource = "" And ctl.Tag <> "c" Then
ctl.Value = Null
End If
Case Else
End Select
Next ctl

End Function

then behind a button: ClearAll("c", Me.Form)

When I tried to use it I recivced an error msg: exspected = sign
and...... of course, functions return values, and non are being asked for so an error would be exspected
Next tried: Call ClearAll("c", Me.Form) and this works, so is the above a function or a public sub, and if its a public sub the above imply's that
call function = public sub ?.

In general: A function returns a value and a Public Sub exacutes a procedure, is this right ?. Any help in clearing up my confusion is appriciated
 
First, replace this:
If ctl.ControlSource = "" And ctl.Tag <> "c" Then
with this:
If ctl.ControlSource = "" And ctl.Tag <> c Then

Then, as you don't expect any return value, change your Function to a Sub.
You may call it either like this:
Call ClearAll("c", Me.Form)
or this:
ClearAll "c", Me.Form

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thank you PHV, I will do so and in general if you expect a value then a function and execute a process a sub.
 
In vb functions return values and subs do not return values. If you do not return a value then use a sub for clarity. It is probably a little faster.

With a function that returns a value you can choose to have it return a value or tell it not to return a value. If you plan to do something with the return value then you have to use parentheses around the parameters

Example

Public Function getTest(strNumber As String) As String
getTest = "Test " & strNumber
MsgBox getTest
End Function


Public Sub TestFunction()
Dim str As String
str = getTest("One")
End Sub

If you just want the function to execute and not return anything then you can not use parens

Public Sub TestFunction2()
getTest "One"
End Sub


This is like the msgbox function

If MsgBox("Do you want to continsue", vbYesNo) = vbYes Then
MsgBox "Continue"
End If
 
Thank's MajP, I did not know these things, that helped
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top