对于大学设置的电子表格任务,我被要求将VBA用户表单包含在学生数据库电子表格中。我编写了一个子例程,将新学生输入工作表中的特定行(AddStudent)是否有任何明显的原因导致Vba无法正确处理此功能。下面的行显示了我使用过的代码。
Private Sub CommandButton1_Click()
If Me.txtStudent.Value = "" Or Me.txtBirth.Value = "" Or Me.txtFirstAdd.Value = "" Or Me.txtSecondAdd.Value = "" Or Me.txtTown.Value = "" Or Me.txtCounty = "" Or Me.txtPost.Value = "" Then MsgBox "Please fill in all details"
Else
Call AddStudent
End If
End Sub
这是我的第一个VBA任务,我不是程序员,所以我为看似微不足道的问题道歉。(我也有一点格式化问题,因为这是我的第一个堆栈溢出帖子)
按下按钮时,我收到以下错误消息"编译错误;没有IF"
感谢任何有时间在这里帮助我的人。
答案 0 :(得分:0)
将您的MsgBox
声明放在新行:
Private Sub CommandButton1_Click()
If Me.txtStudent.Value = "" Or Me.txtBirth.Value = "" Or Me.txtFirstAdd.Value = "" Or Me.txtSecondAdd.Value = "" Or Me.txtTown.Value = "" Or Me.txtCounty = "" Or Me.txtPost.Value = "" Then
MsgBox "Please fill in all details"
Else
Call AddStudent
End If
End Sub
推理:VBA允许您将If {condition} Then {Action}
作为单个语句执行,但是当您以这种方式构造代码时,您不能拥有Else
子句。它基本上是速记的一种方式:
If {condition} Then
{Action}
Else
'Do Nothing
End If
此外,如果您有多个OR
条件,则可以使用Case
语句改善易读性:
Private Sub CommandButton1_Click()
Select Case ""
Case Me.txtStudent.Value, Me.txtBirth.Value, Me.txtFirstAdd.Value, Me.txtSecondAdd.Value, Me.txtTown.Value, Me.txtCounty, Me.txtPost.Value
MsgBox "Please fill in all details"
Case Else
Call AddStudent
End Select
End Sub