Validate numbers to nearest 0.5

AdmiralJonB

New member
Local time
Today, 22:12
Joined
Nov 23, 2004
Messages
7
I'm trying to create some vb code to create some kind of validation so i can check whether a number inputted is 1dp and to a half e.g. 0.0, 0.5, 1.0, 1.5 etc. This is for a form btw.

I've tried with the standard validation settings but i can't find a way to do this. I have some code which i made for it but it's either not working properly or i haven't got it running at the right place.

Code:
Dim Validate1 As Integer
    
    Validate1 = WeightWanted.Value * 2
    
    If Validate1 Mod 1 = 0 Then
    Else: MsgBox ("The Value must be to the closest half a kg")
    End If

What I've tried to do, as for some reason when using 'MOD 0.5' it tries to divide by 0, i multiplied it by two so any 0.5 numbers would become integers so could be divisible by 1 with no remainder (I think MOD is the right command to use).

The final thing is where to put the code. I've tried a few things but for some reason it doesn't come up with a message box at all. Would this type of code stop the user from moving to another field?

BTW, one last question. Is there a way to clear all the records from the database and start all autonumbers from the beginning?
 
Would something like the following work:

Code:
if me!myNumber - int(me!myNumber) = 0 or me!myNumber - int(me!myNumber) = .5
    do stuff
end if


???
kh
 
KenHigg said:
Would something like the following work:

Code:
if me!myNumber - int(me!myNumber) = 0 or me!myNumber - int(me!myNumber) = .5
    do stuff
end if


???
kh

I don't think it'll work as what i'm trying to edit is either the field entering code in the form or the forms code. What I really need to know is which private sub i should put it in.
 
Last edited:
Code:
Private Sub myTextBox_BeforeUpdate(Cancel As Integer)

If Me!myTextBox - Int(Me!myTextBox) <> 0 And Me!myTextBox - Int(Me!myTextBox) <> 0.5 Then
    MsgBox "What ever you want to tell user!"
    DoCmd.CancelEvent
End If

End Sub

???
kh
 
Just a thought - check the functions Round and Fix.
They may do what you need.

Otherwise try Format(<variable>,"#0.0")


Vince
 
The round function is only to a certain amount of decimal places, and the Fix is to Integers only i think. I'm trying out the code by Kenhigg now.
 
I suppose you could simply use this method:

Code:
Public Function ToNearestHalf(ByVal sngValue As Single) As Boolean
    On Error Goto Err_ToNearestHalf
    Dim strNumber As String
    strNumber = Right(Format(sngValue, "0.0", 1)
    If strNumber = 0 Or strNumber = 5 Then
        ToNearestHalf = True
        Exit Function
    End If
Err_ToNearestHalf:
    ToNearestHalf = False
End Sub

And just call it like this:

Code:
If ToNearestHalf(myValue) Then

Else

End If
 
Last edited:

Users who are viewing this thread

Back
Top Bottom