473,701 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generating Random Numbers in VB6

8,435 Recognized Expert Expert
The VB6 Version

Generating a random number is somewhat different in VB6. It's not for me to say which is better, since I'm only familiar with the VB6 method. But certainly generating a random number (more correctly, a pseudo-random number) is simpler in VB6. You simply call the Rnd() function.

This sample form will do the same thing - each time you click the button, it will display a random number between 1 and 10.

To use this code, start a new project in VB6. Create a new form, and add a command button. Change the name of the command button to "cmdRandom" .

If you then double-click the form you will see an "empty" window code template, which should look fairly similar to this...
Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2.  
  3. Private Sub Form_Load()
  4.  
  5. End Sub
Select the entire window (just press Ctrl-A) then paste this code to replace it...
Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2. DefLng A-Z
  3.  
  4. Private Sub Form_Load()
  5.   ' At startup, "seed" VB's pseudo-random number generator.
  6.   Randomize
  7. End Sub
  8.  
  9. Private Sub cmdRandom_Click()
  10.   ' Each time the button is clicked, display
  11.   ' a message box showing a random number between 1 and 10.
  12.   MsgBox "The random number generated is: " & Format(RandomNumBetween(1, 10))
  13. End Sub
  14.  
  15. Private Function RandomNumBetween(ByVal LowerLimit As Long, ByVal UpperLimit As Long) As Long
  16.   ' This function returns a pseudo-random number between
  17.   ' the specified limits (inclusive).
  18.   RandomNumBetween = Rnd * (UpperLimit - LowerLimit) + LowerLimit
  19. End Function
For those who prefer it, I'll attach a copy of the Frm file which you can simply add to your project.

There are a couple of things which are perhaps worth mentioning here...
  • From the look of it, this won't apply in VB.Net, but in VB6 it's a good idea to encapsulate your random number generation within a function like this. It's easy to forget the right procedure for generating a random number between two limits, and people tend to end up with numbers that occasionally fall outside the limits, causing program bugs. Setting up a common function like this which you always use in the future prevents this kind of bug.
  • You may have noticed the Option Explicit at the tiop of the code. If your VB installation doesn't insert this automatically, you should pull down to the Tools menu, select [b]Options, go to the Editor tab, and tick the option Require Variable Declaration. A discussion of this option will be posted here soon, but in the meantime, take it from me - this will prevent lots of bugs.
  • Perhaps you also noticed the DefLng A-Z. This simply instructs VB to use Long as the default data type for all variables, if you don’t specify another type. Whenever you are working with whole numbers, the Long data type is generally to be preferred, unless you have a specific reason to avoid it. Being the native data type on a 32 bit processor, it requires less conversion and is therefore slightly faster to process.
Attached Files
File Type: zip Form1.zip (725 Bytes, 2788 views)
May 4 '07 #1
2 86297
Hitronic
1 New Member
There is an significat Problem in the main Function RandomNumBetwee n :
If you use the automatic VB Conversion from Double/Single to Int VB uses the Round Function
and this leads to a mathematically uneven distribution.
The smallest and largest values occur only half as often.

Here is a (hopefully) correct version :

Expand|Select|Wrap|Line Numbers
  1. Private Function RandomNumBetween(ByVal LowerLimit As Long, ByVal UpperLimit As Long) As Long
  2.    ' This function returns a pseudo-random number between
  3.    ' the specified limits (inclusive).
  4.    RandomNumBetween = Int (Rnd * (UpperLimit + 1 - LowerLimit)) + LowerLimit
  5. End Function
Sep 16 '23 #2
Tomas Fok
1 New Member
Nowadays, ensuring the security of one's own home is becoming a priority for many. With the increasing threat of intrusion and crime, professional CCTV camera installation services are becoming a key part of the security system, ensuring that your home is always monitored and protected.
https://sense-group.pro/network-cabling/
Professional services provide access to advanced technology in the field of video surveillance. These include cameras with various functionalities : indoor, outdoor, night vision, high resolution, etc. Specialists recommend and install the equipment according to the specific needs of the client.

The installation stage plays a crucial role in ensuring the reliability of the system. The experts not only place the cameras in strategic locations, but also configure them for maximum efficiency. This includes optimizing viewing angles, motion sensitivity, and other parameters that allow the system to respond to potential threats.
Nov 21 '23 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
30923
by: Intaek LIM | last post by:
generally, we use srand(time(0)) to generate random numbers. i know why we use time(0), but i can not explain how it operates. first, see example source below. --------------------------------------------- #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv)
2
1770
by: Mike P | last post by:
I have a method that I am using to generate random numbers using Random.Next. However, every time I call the method I get the same random number. Is there a C# equivalent of Randomize is VB6? Thanks, Mike
10
1692
by: Glenn Wilson | last post by:
I have a quick Question and I Hope some one can help or at least explain. What is happening is that I am trying to use random numbers in an application, as per the sample test code below. When I run this code the random numbers that are displayed are all the same for abot 25 cycles and then randomize as normal. Can some one tell me why this is or at least tell me what I am doing wrong. Regards Glenn Module Module1
5
5717
by: dav3 | last post by:
I have almost completed a monster assignment on sorting algorithms (quick, insertion and selection) using c++ but I am lost on one part of the assignment. I have to generate a random list of numbers in reverse order as follows "list = 25.88 - sqrt(i)" and perform all my sorting functions no this list. I have successfully run my program on numerous lists of random numbers.. I just have no clue how to get a reverse generated list of random...
1
2673
by: Velhari | last post by:
Hi, I am a beginner. Please tell me, For generating Random Numbers, Initially why we are going for seed method. And another question is that, I want to print unique random number how to print by using rand() method to print unique random number. And finally i want to know, If a program generate random numbers and the same program will execute after 100 or some days, it will not to generate the old random number (i.e the random number...
8
25471
by: kiranchahar | last post by:
Hey all, How do I generate random numbers with Uniform distribution Uniform(a,b) using C-programming? I want to generate uniform random numbers which have mean following Uniform(p,q) and also variance as Uniform(s,t)? any suggestion would be really appreciated. Thanks, Kay
0
26009
SammyB
by: SammyB | last post by:
These are some "random" thoughts about generating random numbers in Visual Basic. Wikipedia will give a better introduction than I, see http://en.wikipedia.org/wiki/Random_number_generator. The key point is that you need to start the random number generator with a seed. Doing it in the form load with the number of milliseconds since midnight is an easy way to start. The VB.Net version This demo project will be as simple as I can...
2
1551
by: enrique21 | last post by:
Im trying to generate random numbers using the statement: Random r = new Random(2); for (int i=1;i<=18;i++) but im having errors in my results here is my entire code so far: import java.util.*; public class Random4 {
12
2971
by: 9966 | last post by:
Greetings, This is my second post till now. Thanks for all the advice given to me for the first post. Now I'm having problem with generating random numbers. I know if we want to generate a random number, we can use: int tempNUM = rand(); But, once I execute the program, the generated number is always similar, and I found this from the internet. It says need to add this line to make the numbers generated differently:
3
3942
by: diggity | last post by:
okay, so i started on code for Sudoku on ready to program java ... very close to java. I was able to create a 2d array and display and change the variables. What i want to do now is to generate random numbers in the array. Numbers in between 1 and 9. and then i need to check for rows, columns and the boxes... i am new to arrays and i really need some help. // The "Sudoku" class. import java.awt.*; import hsa.Console; public class Sudoku...
0
8732
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9082
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8975
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8933
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5904
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4661
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.