我正在尝试限制文本框在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
答案 0 :(得分:0)
如果要万无一失,可以做一点事情。并不是说这是您想要的解决方案的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
它使用enter和exit事件尝试将单元格从输入重新格式化为输出。
我希望它会有所帮助,并希望我已经对其进行了足够的测试以确保其正常工作。 :-)