我试图在 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
如果你想万无一失,还有一些事情要做。并不是说这 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
它使用进入和退出事件来尝试将单元格从输入重新格式化为输出。
我希望它有所帮助,我希望我已经对其进行了足够的测试以确保它运行良好。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句