使用excel vba验证用户表单数据

时间:2018-05-23 05:36:59

标签: forms excel-vba validation vba excel

我正在编写代码以通过用户表单填充单元格。我需要检查数据是否介于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

` 代码有效,但令人恼火的问题是在我输入数字之前,警报弹出。我怎么能避免它?

1 个答案:

答案 0 :(得分:0)

修改后的代码如下。

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