What is the difference between Sub and Function in VB6?

I am going through some old VB code and I run into function definitions like these -

 Private Function ExistingCustomer(Index As Integer, Customer As String) As Integer

 Private Sub cmdCustomerList_Click()

What's the difference?


Function returns value, Sub doesn't. It's that simple.


A function can also be used in an expression. A Subroutine cannot. Functions can lend to the readability of your code better than a subroutine.

Here's an example of how a function can increase readability:

If AccountIsLocked("JJones") then Msgbox("This account is locked")

this function would be defined somewhere

public function AccountIsLocked(UserId as string) as boolean
   dim usr = uow.AccountRepository.UserInfo(UserId)
   return usr.locked
end function

Here's the same example but coded with a subroutine:

CheckIfAccountLocked("JJones")

and elsewhere this sub is defined:

public sub CheckIfAccountLocked(UserId)
       if uow.AccountRepository.UserInfo(UserId).locked then
          msgbox("Account is locked")
       end if
end sub

Also note that checking the value is separated from the action -- this contributes to separation of duties. The function would lend toward re-usability.

With VB6 there are some odd rules governing parenthesis. If there are no parameters to a sub then the parenthesis are not needed (I think Visual Studio might remove the parenthesis). One way around this is to add the keyword "Call" before your sub.

Call CheckIfAccountLocked()

vs

CheckIfAccountLocked

In function we can return values as boolean, string and other data data types.

but sub does not return any thing. it just executes code and instruction that we give. These are also regarded as methods

Sub is also used in control's events and these events also not return any value.

for example the click event of a command button: Private sub cmd_click()

end sub