Harry
Harry

Reputation: 15

VBA decimal places program

I need a program that requires the user to provide a number with no more than 2 decimal places, and if a number with more than 2 decimals is given to loop back and ask again. Then to be able to output that number with the corresponding decimal places. This is what I have so far...

Sub program()
   Dim num as Double

   num = Inputbox("Give me a number with no more than 2 decimal places:")

   MsgBox "Your time was " & num & " seconds."
End Sub

Upvotes: 1

Views: 90

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149287

Instead of Inputbox use Application.InputBox with Type:=1. This will ensure only numeric entries.

Is this what you are trying? This will allow values like 1,1.1,1.11,.1,.11

Sub Sample()
    Dim Ret
    Dim digitsAfterDecimal As Integer

    Do
        Ret = Application.InputBox(prompt:="Enter a number with max 2 decimal places", Type:=1)

        '~~> If user presses cancel
        If Ret = False Then Exit Do

        '~~> Number of digits after decimal
        digitsAfterDecimal = Len(CStr(Ret)) - InStr(CStr(Ret), ".")

        '~~> This will allow up to 2 decimal
        If digitsAfterDecimal < 3 Then Exit Do
    Loop

    If Ret <> False Then MsgBox Ret
End Sub

Upvotes: 1

Related Questions