VBA Userform输入验证错误

时间:2013-07-29 02:00:47

标签: excel validation vba excel-vba userform

我是VBA的新手,我的问题可能很愚蠢,但我无法解决,所以如果可以,请帮助我!

事情就是这样:我得到了完全填充电子表格的用户形式,但是如果没有输入信息,它就会做出疯狂的事情。正如您在下面看到的,我找到了一些代码来检查是否输入了数据,因此如果没有弹出窗口,您必须输入内容,但是当您执行表单时,将填充2行数据而不是1行。例如,如果选择行'x'并且想要将值'a','b','c','d',但忘记放置值'c',那么它会显示错误,当我输入缺失值时' c'然后按OK它会创建行'​​x',其值为'a','b','','d'和行'x + 1',值为'a','b','c','d ”。 这是我的代码:

Private Sub cmdok_Click()
'next empty cell in column A
Set c = Range("a65536").End(xlUp).Offset(1, 0)
  Application.ScreenUpdating = False    'speed up, hide task
'write userform entries to database
c.Value = Me.txtFname.Value
c.Offset(0, 3).Value = Me.txtngoals.Value
c.Offset(0, 28).Value = Me.cmbDiag.Value

 If Me.optAcute.Value = "True" And Me.optchronic.Value = "False" Then
   c.Offset(0, 29).Value = 1
   c.Offset(0, 30).Value = ""
 Else
   c.Offset(0, 29).Value = ""
   c.Offset(0, 30).Value = 1
 End If

'input validation
 If txtFname.Value = "" Then
  MsgBox ("Sorry, you need to provide a Name")
  txtFname.SetFocus
 Exit Sub
 End If

 If txtngoals.Value = "" Then
  MsgBox ("Sorry, you need to provide goals")
  txtngoals.SetFocus
 Exit Sub
 End If

 If cmbDiag.Value = "" Then
  MsgBox ("Sorry, you need to provide Diagnosis")
  cmbDiag.SetFocus
 Exit Sub
 End If

 If optAcute.Value = optchronic.Value Then
  MsgBox ("Sorry, you need to select Time since injury")
  Exit Sub
 End If

'clear the form
With Me
    .txtFname.Value = vbNullString
    .cmbDiag.Value = vbNullString
    .optAcute.Value = vbNullString
    .optchronic.Value = vbNullString
    .txtngoals.Value = vbNullString
End With
Application.ScreenUpdating = True

End Sub

提前谢谢

1 个答案:

答案 0 :(得分:1)

尝试在验证检查后将代码“将用户表单条目写入数据库”。

Private Sub cmdok_Click()
'next empty cell in column A
Set c = Range("a65536").End(xlUp).Offset(1, 0)
  Application.ScreenUpdating = False    'speed up, hide task

'input validation
 If txtFname.Value = "" Then
  MsgBox ("Sorry, you need to provide a Name")
  txtFname.SetFocus
 Exit Sub
 End If

 If txtngoals.Value = "" Then
  MsgBox ("Sorry, you need to provide goals")
  txtngoals.SetFocus
 Exit Sub
 End If

 If cmbDiag.Value = "" Then
  MsgBox ("Sorry, you need to provide Diagnosis")
  cmbDiag.SetFocus
 Exit Sub
 End If

 If optAcute.Value = optchronic.Value Then
  MsgBox ("Sorry, you need to select Time since injury")
  Exit Sub
 End If

'write userform entries to database
 c.Value = Me.txtFname.Value
 c.Offset(0, 3).Value = Me.txtngoals.Value
 c.Offset(0, 28).Value = Me.cmbDiag.Value

  If Me.optAcute.Value = "True" And Me.optchronic.Value = "False" Then
    c.Offset(0, 29).Value = 1
    c.Offset(0, 30).Value = ""
  Else
    c.Offset(0, 29).Value = ""
    c.Offset(0, 30).Value = 1
  End If    

'clear the form
With Me
    .txtFname.Value = vbNullString
    .cmbDiag.Value = vbNullString
    .optAcute.Value = vbNullString
    .optchronic.Value = vbNullString
    .txtngoals.Value = vbNullString
End With
Application.ScreenUpdating = True