0
Private Sub cmdAdd_Click()
If cmdAdd.Caption = "ADD" Then
txtName.Enabled = True: cboAge.Enabled = True:
cmdAdd.Caption = "SAVE": cmdClose.Caption = "CANCEL"
txtName.SetFocus
Else
If txtName.Text = "" Or cboAge.Text = "" Then
MsgBox "Required field(s) missing!", vbCritical, "Message"
Else
For i = 2 To Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
If (txtName.Text) = Sheet1.Cells(i, 1).Value Then
MsgBox "Record already exist!", vbExclamation, "Message"
Call UserForm_Activate
Exit Sub
End If
Next i
r = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1
Sheet1.Cells(r, 1).Value = (txtName.Text)
Sheet1.Cells(r, 2).Value = cboAge.Text
r = 0
MsgBox "One record saved!", vbInformation, "Message"
Call UserForm_Activate
End If
End If
End Sub*

此代码用于在工作表中添加名称和年龄,我的问题是工作表中已经存在名称和年龄,但是如果我要添加相同的名称但不同的年龄,它无法添加,即使信息不一样。希望你能帮助我提前谢谢

4

1 回答 1

0

您只是在测试名称是否相同,如果相同则退出。要测试姓名和年龄是否相同,请更改以下内容:

If (txtName.Text) = Sheet1.Cells(i, 1).Value Then
MsgBox "Record already exist!", vbExclamation, "Message"

对此:

If txtName.Text = Sheet1.Cells(i, 1).Value And _ 
    cboAge.Text = Sheet1.Cells(i, 2).Value Then
MsgBox "Record already exist!", vbExclamation, "Message"
于 2013-09-21T15:53:43.267 回答