我有一个工作簿,其中包含4个工作表,每个工作表在2019年占四分之一。
我想编写一个函数来检查活动单元格的输入是否是从活动单元格行到最后一个工作表末尾的重复项。
Function checkDuplicate(ByVal ChangedCell As Range) As Boolean
TelNo = ChangedCell.Value
Range(ActiveCell.Address).Name = "StartCell"
For i = ActiveSheet.Index To ActiveWorkbook.Worksheets.count
Worksheets(i).Activate
With Worksheets(i)
Set rng = Cells.Find(What:=TelNo, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
End With
Next i
Application.Goto "StartCell"
If rng Is Nothing Then
checkDuplicate = False
Else
checkDuplicate = True
End If
但是,似乎它甚至无法在活动单元格下面的行中找到重复的值。
答案 0 :(得分:1)
就目前而言,您的循环毫无用处。您可以使用完全相同的结果执行此操作:Set rng = Worksheets(4).Cells.Find(What:=TelNo, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
尝试一下:
Function checkDuplicate(ByVal ChangedCell As Range) As Boolean
TelNo = ChangedCell.Value
Range(ActiveCell.Address).Name = "StartCell"
Set rng = ActiveSheet.Cells.Find(What:=TelNo, After:=changedCell LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rng Is Nothing And rng.Address <> ChangedCell.Address Then checkDuplicate = True
If ActiveSheet.Index < ActiveWorkbook.Worksheets.Count Then
For i = ActiveSheet.Index + 1 To ActiveWorkbook.Worksheets.count
With Worksheets(i)
Set rng = .Cells.Find(What:=TelNo, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rng Is Nothing Then checkDuplicate = True
End With
Next i
End If
End Function
注意,我在.
通话之前添加了range.find
。这是为了使With Worksheets(i)
生效。这也是我删除Worksheets(i).Activate
的原因,因为在完全排纸时不必这样做。
需要注意的另一件事:Range(ActiveCell.Address).Name = "StartCell"
隐式调用了ActiveSheet
。
通常应避免在代码中使用ActiveSomething
,因为它会导致大量错误。