I wanted to generate a random number between 1 and 20 for a game that I am creating and for some reason this code has stopped working and gives me a type mismatch error, I have tried other generators in the game but I get the same error.
Public Counter1 As Integer ' Counters for each reel
Public ArrayImgMid1 As Integer ' Store number to iterate over image arrays
Public ReelPic1 As Variant ' Array of images for each reel
Public Reel1Spin As Long ' Spins for each reel
Public ImgBeth, ImgWallow, ImgDan, ImgChris, ImgCatBug As StdPicture ' Images for reels
Private Sub CmdSpin_Click()
'Enable all timers to imitate spinning
TimerReel1.Enabled = True
TimerReel1.Interval = 100
' Disable spin button
CmdSpin.Enabled = False
' Set all counters to 0
Counter1 = 0
' Generate random number for the first reel to spin
Reel1Num = (CLng(Rnd * 20) + 1) ' This is highlighted when I press debug
Write it like this:
Dim Reel1Num As Long Reel1Num = (CLng(Rnd * 20) + 1)
Integer in VB6 - it represents a 16-bit signed integer and it has slightly less performance than
Long which is really a 32-bit signed integer. This way you also won't run into limits with the 16-bit data type.
The reason your code doesn't work is because the
Int() function doesn't convert the data type of a value to type
Integer - it rounds the specified value to an integer value but keeps its data type.
To convert a value to a particular data type, use the
CLng(), etc. functions. But as I said, avoid using
Integer unless you specifically need it -
Long is better in most cases.
After you posted your code, I can't see a definition of the
Reel1Num variable - where is it defined? Is it
Reel1Spin? If that's the case, make sure you enable the
Require variable declaration option in
Tools->Options - it's off by default. If you don't have it on, it's a very easy way to shoot yourself in the foot.
Unrelated to your error, but most of your image objects are defined incorrectly - in VB6, the type of a variable must be specified for every variable, not once per line. So on this line:
Public ImgBeth, ImgWallow, ImgDan, ImgChris, ImgCatBug As StdPicture
you only really create 1
StdPicture object, all others will be variants. The right way to do it is:
Public ImgBeth As StdPicture, ImgWallow As StdPicture, ImgDan As StdPicture, _ ImgChris As StdPicture, ImgCatBug As StdPicture
Aside from these, I can't see anything wrong with your code - I don't have VB6 installed on my computer. Keep in mind, that VB6 had a funky way of dealing with type mismatch and in some cases the highlighted line may not be the one that causes the actual error. This used to drive me crazy.