Skip to content

Passing values between subs and/or functions in VB 2005

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #190371
    autopilot
    Member

    To do things in VB, you can use subs and or functions.

        Private Sub DoTask()
    ' Do Task1
    Call Task1()
    ' Do Task2
    Call Task2()
    ' Do Task3
    Call Task3()
    End Sub

    Private Sub Task1()
    MessageBox.Show("Hello", "Task1")
    End Sub
    Private Sub Task2()
    MessageBox.Show("Hello", "Task2")
    End Sub
    Private Sub Task3()
    Dim i As Integer
    i = 3 + 5
    MessageBox.Show(i.ToString, "Task3")
    End Sub

    Now the above sample will process each task in order, but can not pass any information to the tasks or recieve information back from the tasks. We can pass values to a sub by declaring them in the ()

        Private Sub DoTask()
    ' Do Task1
    Call Task("Hello", "Task1")
    ' Do Task2
    Call Task("Hello", "Task2")
    ' Do Task2
    Call TaskAdd(3, 5)
    End Sub

    Private Sub Task(ByVal sMessage As String, ByVal sTitle As String)
    MessageBox.Show(sMessage, sTitle)
    End Sub
    Private Sub TaskAdd(ByVal i1 As Integer, ByVal i2 As Integer)
    Dim i As Integer
    i = i1 + i2 ' Add i1 and i2
    MessageBox.Show(i.ToString, "Task3")
    End Sub

    In this fashion, we can make a task that can take in values and then act on them. But how do we get a value back from a task? So far I have been using “Sub” as my task type. Lets now use “Function” in place of “Sub”.

        Private Sub DoTask()
    ' Do Task1
    If Task("Hello", "Task1") Then
    ' if true is returned then do Task2
    Task("Hello", "Task2")
    Else
    ' If false is returned do Task3
    Dim i As Integer = TaskAdd(3, 5)
    MessageBox.Show(i.ToString, "Task3")
    End If
    End Sub

    Private Function Task(ByVal sMessage As String, ByVal sTitle As String) As Boolean
    ' Initialize the random-number generator.
    Randomize()
    ' Generate random value between 1 and 6.
    Dim i As Integer = CInt(Int((6 * Rnd()) + 1))
    ' Add i to sMessage and show in a messagebox
    MessageBox.Show(sMessage & " " & i.ToString, sTitle)
    If i > 3 Then
    Task = True
    Else
    Task = False
    End If
    End Function
    Private Function TaskAdd(ByVal i1 As Integer, ByVal i2 As Integer) As Integer
    TaskAdd = i1 + i2
    End Function

    This is the basic way that you can pass value(s) to a task and get a value returned from a task.
    Happy coding!

    autopilot

    #190377
    autopilot
    Member

    In the previous post, we showed how to pass values to a Sub or Function and how to pass a value back from a Function. What about passing values back from a Sub? With a Sub, to pass a value to it, we used ByVal to define what we will being passed in. To pass something back out, we will use ByRef.

        Private Sub DoTask()
    Dim i1, i2 As Integer
    ' Initialize the random-number generator.
    Randomize()
    ' Generate random value between 1 And 6.
    i1 = CInt(Int((6 * Rnd()) + 1))
    DoTask1(i1, i2)
    MessageBox.Show(i2.ToString, "Results")
    End Sub

    Private Sub DoTask1(ByVal intPass As Integer, ByRef intReturn As Integer)
    intReturn = intPass + 10
    End Sub

    Now you might ask, why use a Function when a Sub can do the same thing? Well for very short Subs such as the example, it will not matter. But for longer Subs, the results could be very troublesome. To put it in a nutshell, if you use a Function, it will execute and compleate before the calling Sub or Function goes to the next step. If you use a Sub, the calling Sub or Function will not wait for it to complete before continuing. So now create your own Subs and Functions and get test out passing values for yourself. The ByRef can be used with Functions as well. So don’t be afraid to try using it!

        Private Sub DoTask()
    Dim i1, i2 As Integer
    Dim s As String
    ' Initialize the random-number generator.
    Randomize()
    ' Generate random value between 1 And 6.
    i1 = CInt(Int((6 * Rnd()) + 1))
    s = DoTask1(i1, i2)
    MessageBox.Show(i2.ToString, "Results: " & s)
    End Sub

    Private Function DoTask1(ByVal intPass As Integer, ByRef intReturn As Integer) As String
    intReturn = intPass + 10
    If intReturn > 13 Then
    DoTask1 = "Hi"
    Else
    DoTask1 = "Low"
    End If
    End Function

    Happy coding

    autopilot

    #190376
    Chike
    Member

    @autopilot wrote:

    To put it in a nutshell, if you use a Function, it will execute and compleate before the calling Sub or Function goes to the next step. If you use a Sub, the calling Sub or Function will not wait for it to complete before continuing.

    Are you sure about this?
    Haven’t seen any mention of it in the [url url=ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_vbalr/html/e347d700-d06c-405b-b302-e9b1edb57dfc.htm:14vuoq1s]documentation[/url:14vuoq1s]
    The only difference that is stated in the documentation is the return value, and the context it can be declared. Just as Pascal has procedures and C the special type void for functions that do not return a value.

    @autopilot wrote:

    Well for very short Subs such as the example, it will not matter. But for longer Subs, the results could be very troublesome.

    If it is true, then the size of the sub does not matter, and if it does work it’s only coincidental.

    #190375
    autopilot
    Member

    @Chike wrote:

    Are you sure about this?
    Haven’t seen any mention of it in the [url url=ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_vbalr/html/e347d700-d06c-405b-b302-e9b1edb57dfc.htm:2ymeq02r]documentation[/url:2ymeq02r]

    nope… i’m not sure… and in fact, if you pass a ByRef object, it is not true. but if you do not pass a byref object, then from experience, i can tell you that the executing code will not wait..

    did i state it correctly? nope… and problably still have not… will it, as stated, help some others avoid problems that i was running into when i first started writing apps? i hope so…

    am i an authority on the VB (or any other) programming language? by no means!!!! but i do alot of google searches and reading… then i play with codes until i can get it to do what i am trying to do. i have no programming schooling and learned everything i know by trial and error and reading on line. so when i create a post like this, i am by no means trying to state that i have all the answers… the point of this post is to help those with no experience see in a plain english way how to do the basics… and if the explanation is not 100% acurate, then they start out with a slightly wrong definition… but the concept of the post was still grasped and they can start doing things with their programs because now they have the understanding that they can pass objects to and from subs and/or functions.

    it was only about 2 or 3 years ago that i started writing any apps… and as i have a fulltime job doing things other then programming, and as i have not taken any classes on programming, i had written this post because it was something that was not made real clear in alot of the information that i was reading.

    my hope is that other new hobbiest coders will get a better idea of how they can expand their programs and start sharing with the community. that is why i have shared not only compiled programs, but alot of my code as well… is my code perfect? probably not even close… but if it can help others who in turn help more, then thats what it is all about…

    #190374
    Chike
    Member

    LOL no need to go defence, i was just pointing the posibility of an error, and after all it is a tutorial so you may want it to be corrected if needs to be.
    Just as you are self tought, peaople are learning from your code, and I am sure you don’t want them to learn wrong concepts.

    I don’t believe the behavior of a sub depends on it’s parameters, if any at all. So here a simple way for testing it.
    pseudo code (as my basic skills are limited):

    sub sub1(byval var1 as integer)
    // pause for a second by means provided by basic or windows api, or even a long loop
    // write to console or any other method that can be observed, or just set a breakpoint
    end sub

    sub sub2
    call sub1
    // write to console or any other method that can be observed, or just set a breakpoint
    end sub

    I am quite sure the result wil be the same no matter how many times you repeat it or how long the pause will be, sub2 will always wait for sub1 to complete. You may correct me if I am wrong.
    For what I can see, and know from other languages, subs are just the same as functions aside from the return value.

    #190373
    Departure
    Member

    hmmm im not sure about vb.net but I have always been told
    Function returns a value and subs dont, its that simple and thats what I code my programs to.

    in delphi functions return a value and procedures dont, They are the only 2 languages I play with, its been a while with vb6, but delphi is that way. So for you to get a retun value from a sub could be very well possiable but I have always thought sub are to do a task and also to pass values to the sub not get a return value.

    #190372
    Chike
    Member

    Sure you can think of cases where you want a sub to perform an operation on a structure and modify it, or perform a task that return more than one value, or as array, which cannot be returned as a function result. But if you need to know if it succeeded or not you make it a function for convenience.
    For example GetWindowText function, you could do without the return value and just initialize the string before call and check it after it, but the return value save all that work.
    And sub that has 2 return values like:
    sub divide(byval numerator as integer, byval denominator as integer, byref quotient as integer, byref remainder as integer)

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.