我想對重復記錄實施安全檢查,如下所示:
- 通知用戶,如果他/她添加了表中已存在的 ID(同一張表)
- 通知用戶,如果他/她添加了其他檔案中已存在的 ID(通過 PowerQuery 加載為 ListObject 的資料)
下面的腳本應該注意以上幾點。它適用于第一點并通知用戶,如果他/她添加了多次出現的 ID。但是,如果用戶在串列物件“資料”和“ID”列中添加已出現在“資料”表上的 ID,則它什么也不做
Private Sub Worksheet_Change(ByVal target As Range)
Dim count As Long
'1. This checks, whether the ID already exists in the same sheet and appears more than once
If target.Column = 2 Then
If target.Cells.count = 1 Then
count = Application.WorksheetFunction.CountIf(Tracker.ListObjects(1).ListColumns("ID").DataBodyRange, target.Value)
If count > 1 Then
MsgBox "WARNING: ID " & target.Value & " already exists in the table."
End If
End If
'2. This checks, whether the ID already exists in the other files
Else
If target.Cells.count > 0 Then
count = Application.WorksheetFunction.CountIf(Data.ListObjects("Data").ListColumns("ID").DataBodyRange, target.Value)
If count > 0 Then
MsgBox "WARNING: ID " & target.Value & " already exists in other trackers."
End If
End If
End If
End Sub
有什么想法或建議,有什么問題嗎?
uj5u.com熱心網友回復:
據我了解您的代碼,ID 輸入在第 2 列中,但是只有在任何其他列中輸入了某些內容時,才會對 ListObject 進行檢查(因為您將檢查放在Else-branch 中)。我想以下應該可以解決問題
Private Sub Worksheet_Change(ByVal target As Range)
Dim count As Long
If target.Column <> 2 Then Exit Sub
If target.Cells.count <> 1 Then Exit Sub
'1. This checks, whether the ID already exists in the same sheet and appears more than once
count = Application.WorksheetFunction.CountIf(Tracker.ListObjects(1).ListColumns("ID").DataBodyRange, target.Value)
If count > 1 Then
MsgBox "WARNING: ID " & target.Value & " already exists in the table."
Exit Sub
End If
' 2. This checks, whether the ID already exists in the other files
count = Application.WorksheetFunction.CountIf(Data.ListObjects("Data").ListColumns("ID").DataBodyRange, target.Value)
If count > 0 Then
MsgBox "WARNING: ID " & target.Value & " already exists in other trackers."
End If
End Sub
我強烈建議學習如何使用除錯器——如果你一步一步地執行代碼,這些問題通常很容易檢測到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/387211.html
