正如标题所述,我想检查函数内部某个值是否已经在工作簿内部。我当前的思维过程是遍历所有工作表,同时检查要查找的值是否出现在范围的任何单元格中。
出于某种原因,此代码实际上会查找重复值,但只在1个工作表中查找(忽略其他工作表)。
Public Function foundDuplicateID(cellValue As Double) As Boolean
Dim Rng As Range
Dim cell As Range
Dim duplicatesFound As Integer
duplicatesFound = 1 ' Initializing as 1 since the first "duplicate" is the number that is searched for itself
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
Application.ScreenUpdating = False
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
Current.Activate
' Value Range (Same range for all worksheets)
Set Rng = Range(Range("B7"), Range("B" & Rows.Count).End(xlUp)
If Not Rng.Find(cellValue, , Excel.xlValues) Is Nothing Then
duplicateFounds = duplicateFounds + 1
End If
Next
If duplicatesFound = 1 Then
foundDuplicateID = False
ElseIf duplicatesFound > 1 Then
foundDuplicateID = True
End If
End Function
答案 0 :(得分:1)
您最有可能在该单元格中将该函数用作UDF。但是UDF无法更改与UI的交互,因此它们不能激活不同于当前活动的工作表。
更改循环代码以引用Current
表,如下所示:
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
With Current ' reference current sheet
' Value Range (Same range for all worksheets)
Set Rng = .Range(.Range("B7"), .Range("B" & Rows.Count).End(xlUp)) ' each referenced sheet members are a simple dot away from it
If Not Rng.Find(cellValue, , Excel.xlValues) Is Nothing Then duplicateFounds = duplicateFounds + 1
End With
Next
此外,您在某些duplicatesFound
变量引用中有错别字:使用Option Explicit
可以抓住它们(并有其他好处)
Option Explicit
Public Function foundDuplicateID(cellValue As Double) As Boolean
Dim Rng As Range
Dim duplicatesFound As Integer
duplicatesFound = 1 ' Initializing as 1 since the first "duplicate" is the number that is searched for itself
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
Application.ScreenUpdating = False
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
With Current
' Value Range (Same range for all worksheets)
Set Rng = .Range(.Range("B7"), .Range("B" & Rows.Count).End(xlUp))
End With
If Not Rng.Find(cellValue, , Excel.xlValues) Is Nothing Then duplicatesFound = duplicatesFound + 1
Next
foundDuplicateID = duplicatesFound > 1
End Function
进一步重构代码将导致:
Option Explicit
Public Function foundDuplicateID(cellValue As Double) As Boolean
Dim duplicatesFound As Long ' better use Long instead of Integer and avoid overflow issues
Dim Current As Worksheet
Application.ScreenUpdating = False
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
With Current ' reference current sheet
If Not .Range(.Range("B7"), .Range("B" & Rows.Count).End(xlUp)).Find(cellValue, , Excel.xlValues) Is Nothing Then duplicatesFound = duplicatesFound + 1
End With
Next
foundDuplicateID = duplicatesFound > 0
Application.ScreenUpdating = True
End Function