0

我是 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

结束子

先感谢您

4

1 回答 1

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
于 2013-07-29T02:39:54.713 回答