【问题标题】:How to enter a number textbox between 10-50 as a percentage format in vba userforms?如何在 vba 用户窗体中以百分比格式输入 10-50 之间的数字文本框?
【发布时间】:2019-10-09 15:09:13
【问题描述】:

我正在尝试将文本框限制在 10-50 之间,并且它必须采用百分比数字格式。但是,当我尝试下面的代码时,它会向我输入的每个数字发送消息框。我错了什么这段代码?谢谢。

        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

【问题讨论】:

    标签: excel vba textbox userform


    【解决方案1】:

    如果您想做到万无一失,还需要做一些事情。并不是说这是 100% 的您想要的解决方案,但在这段代码中有一些事情需要您自己考虑...

    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
    

    它使用进入和退出事件来尝试将单元格从输入重新格式化为输出。

    我希望它有所帮助,我希望我已经对其进行了足够的测试以确保它运行良好。 :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2018-04-21
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多