我正在编写代码以通过用户表单填充单元格。我需要检查数据是否在 0 和 1 之间并提示用户输入正确的数据。
Private Sub TextBox1_Change()
wt = TextBox1.Value
If wt >= 0 And wt <= 1 Then
Range("Wt!B2").Value = wt
Else
MsgBox "Enter a number between 0 and 1"
End If
End Sub
` 代码有效,但令人恼火的问题是,甚至在我输入数字之前,警报就会弹出。我怎样才能避免它?
修改后的代码如下。
Dim flag As Integer
Private Sub CommandButton2_Click()
If flag = 1 Then
MsgBox "Enter values between 0 and 1"
Else
Range("Wt!B2").Value = TextBox1.Value
Unload Me
End If
End Sub
Private Sub TextBox1_Change()
Dim wt As Double, new_value As Double
TextBox1.SetFocus
If IsNumeric(TextBox1.Value) Then
new_value = CDbl(TextBox1.Value)
Else
new_value = 0
End If
wt = new_value
DataValidate (wt)
End Sub
Sub DataValidate(wt)
If wt >= 0 And wt <= 1 Then
'do nothing
Else
flag = 1
End If
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句