martin2k

ForumsVB6GamesSoftwareDirectoryHTMLArticlesBlogContact

How to create a UDF (User Defined Function) by scott


 

Home

Read and add posts to the Visual Basic 6.0 Forums

Download some of my programs and OCXs

Read the Tips here

The old style forum is still available here

Contact


 

Beginner Tip

Functions are helpful pieces of coding that allow you to run through a series of tasks over and over again. all they need is a name, and optional variables.

let's start with a function for a simple task. for this task we shall define a list of events, and have the function execute them when it is called.Let's start with a random number generator that will create numbers between 1 and 10.

cmd1_Click()
tasks
lbl1.caption = intrandom
end sub

public function tasks
dim intRandom as integer
randomize
intRandom = rnd(1 * 10)
end function

well, that seems kind of pointless, doesn't it? you can execute that code without a function and it would be faster than that. the trick to using a function for simple tasks is calling it from different points in the code, and filling it with as many tasks as you can.

now lets put some purpose into it. now we'll set the upper and lower bounds of the generator.

cmd1_Click()
tasks(10,1)
lbl1.caption = intrandom
end sub

cmd2_Click()
tasks(25,0)
lbl1.caption = intrandom

public function tasks(UpperBound as long,LowerBound as long)

dim intRandom as integer
randomize
intRandom = rnd(LowerBound * UpperBound)
end function

now we give it a bit of purpose. we call it from two different places, and under different circumstances.

also note that I used public instead of private. this means that anything dim'ed inside the function can be used outside the function.

Now we'll take this a bit further. a private function that let's you determine what variable is used.

dim intRandom as integer

cmd1_Click()
random(intRandom,1,10)
lbl1.caption = intrandom
end sub


cmd2_Click()
random(intRandom,0,25)
lbl1.caption = intrandom


cmd3_Click()
random(intRandom,-100,100)
lbl1.caption = intrandom


private function random(InputVariable as long,LowerBound as long,UpperBound as long)

randomize
intRandom = rnd(LowerBound * UpperBound)
end function

their. I believe that's the peak of its performance. we call it from three separate places, specify three requirements, have it listed as a private function, and gave it a worthwhile name. I also changed the order of LowerBound and UpperBound to make more logical sense.


blog comments powered by Disqus
Martin Allen 1999 - 2011.  Last updated Friday 12 August 2011 11:58:06 PM +0100.