简体   繁体   中英

How to enter a number textbox between 10-50 as a percentage format in vba userforms?

I am trying to do give limitations a textbox between 10-50 and it have to be in percentage number format.However, when i tried this code below it sends message box to every number what i have entered.What i wrong with this code? Thank you.

        Private Sub TextBox4_Change()
        If(TextBox4.Value<50 And TextBox4.Value>5) Then
        TextBox4.Value = Format(TextBox4.Value, "0.00%")
        Else 
        Msgbox " Please enter the number between 10 -50"
        End Sub

There's a bit to do if you want to foolproof it. Not saying this is 100% the solution you want but there are a few things considered a in this code that you need to think about yourself ...

Private bIsChanging As Boolean

Private Sub TextBox4_Change()
    Dim dblValue As Double, bIsError As Boolean

    If TextBox4.Text = "" Then Exit Sub
    If bIsChanging Then Exit Sub

    bIsError = True

    If IsNumeric(TextBox4.Text) Then
        dblValue = CDbl(TextBox4.Value)

        If dblValue >= 0 And dblValue <= 50 Then
            bIsError = False
        End If
    End If

    If bIsError Then
        MsgBox "Please enter the number between 1 and 50."
    End If
End Sub

Private Sub TextBox4_Enter()
    On Error Resume Next

    Dim dblNewValue As Double, strFormat As String

    If TextBox4.Text = "" Then Exit Sub
    dblNewValue = CDbl(Replace(TextBox4.Value, "%", ""))

    strFormat = "0"

    If dblNewValue - (1 * (dblNewValue \ 1)) <> 0 Then
        strFormat = "0.00"
    End If

    bIsChanging = True
    TextBox4.Value = Format(dblNewValue, strFormat)
    bIsChanging = False
End Sub

Private Sub TextBox4_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    On Error Resume Next

    bIsChanging = True
    TextBox4.Value = Format(TextBox4.Value / 100, "0.00%")
    bIsChanging = False
End Sub

在此输入图像描述

It uses the enter and exit events to try and reformat the cell from an input to an output.

I hope it helps and I hope I've tested it enough to make sure it works well. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM