如何警告重复条目vba

问题描述 投票:0回答:1

我这里有一个来自 vba 表单的代码,如果满足 2 个条件,它应该发出警告(在“提交”按钮中编码):

Dim ws As Worksheet
Dim rangeID As Long, rangeName As String

rangeID = Application.WorksheetFunction.Countif(ws.Range("A:A"), idField.Value)
rangeName = Application.WorksheetFunction.Countif(ws.Range("B:B"), nameField.Value)

If rangeID >= 1 And rangeName >=  1 Then
MsgBox, "You already have entered this parent."
Else
'Save to excel sheet
End If

现在,假设工作表中存在一个现有的:

ID      NAME 
1110    Michael

当我输入

1110 for ID
Annie for Name
时,它应该保存在工作表中。但是,警告提示。

You already have entered this parent.

当我输入

1111 for ID
Annie for Name
时,警告也会提示。

You already have entered this parent.

这是一个小系统,输入家长的 ID 号和班级中他/她的孩子的姓名。

对于有 2 个孩子的父母,输出应该是:

ID      NAME 
1110    Michael
1110    Annie

如果添加另一位家长和 1 个与上一个条目同名的孩子,则应如下所示:

ID      NAME 
1110    Michael
1110    Annie
1111    Annie

最后的输出是,它应该/绝对不能保存 2 个相同的 ID 和 2 个相同的名称。

ID      NAME 
1110    Michael
1111    Annie   
1111    Annie (it should not be saved to sheet)

我的代码中可能会遗漏什么? TY

excel vba forms duplicates countif
1个回答
0
投票

使用此代码,仅当 ID 和 Name 都存在于同一行时才会触发警告。否则,数据将保存到工作表中。

请务必更新,将“YourSheetName”替换为实际名称。

Dim ws As Worksheet
Dim LastRow As Long, i As Long
Dim IDExists As Boolean, NameExists As Boolean

Set ws = ThisWorkbook.Sheets("YourSheetName") 'Replace with your sheet name

' Find the last row with data in column A
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

IDExists = False
NameExists = False

' Loop through each row to check if both ID and Name exist on the same row
For i = 1 To LastRow
    If ws.Cells(i, 1).Value = idField.Value And ws.Cells(i, 2).Value = nameField.Value Then
        IDExists = True
        NameExists = True
        Exit For
    End If
Next i

If IDExists And NameExists Then
    MsgBox "You already have entered this parent."
Else
    'Save to excel sheet
End If
© www.soinside.com 2019 - 2024. All rights reserved.