我编写了一个 VBA 函数,试图绕过使用数组公式来检查一系列单元格是否符合条件并返回一些列偏移量。它基本上是一个 Sumif,它不是返回一个总和,而是返回一个已经被求和的单元格范围。
我遇到的问题是,在工作表中调用代码与在另一个函数中调用时,代码的运行方式不同,特别是 .SpecialCells 在需要时不会限制范围。例如,在代码中,我只对具有公式或常量的单元格执行比较,这可以很好地限制从另一个宏或即时窗口调用时执行的计算,但如果我将其作为公式输入工作表中,它根本不限制它(如果我指定整个列作为比较,即使列中的大多数单元格都是空白的,它仍然会遍历所有 1048576 个单元格)
重要代码如下:
For Each CheckCell In Check.SpecialCells(xlCellTypeConstants)
对于 Check as Range("A:A"),理想情况下,这将针对其中包含常量的 132 个单元格运行,而是运行整个列。
任何想法如何让它更明智地工作?其余代码可以很好地满足我的需要,我只是不想让它花费几秒钟来计算使用该公式的每个单元格的整个列。
功能齐全:
Function RangeIf(returnColumn As Range, Check As Range, Condition As String) As Range
'Exit Function
Dim Operator As Integer, HasOperator As Boolean, TheColumn As String, CheckCell As Range, Passed As Boolean, ReturnRange As Range
HasOperator = True
Operator = 0
TheColumn = Mid(returnColumn.Cells(1, 1).Address, 2)
TheColumn = "$" & Mid(TheColumn, 1, InStr(1, TheColumn, "$"))
While HasOperator
Select Case Mid(Condition, 1, 1)
Case "<"
Operator = Operator Or 1
Condition = Mid(Condition, 2)
Case ">"
Operator = Operator Or 2
Condition = Mid(Condition, 2)
Case "="
Operator = Operator Or 4
Condition = Mid(Condition, 2)
Case Else
HasOperator = False
End Select
Wend
For Each CheckCell In Intersect(Check, Check.Parent.UsedRange).Cells
Passed = False
'UpdateStatusBar "Processing Cell: " & CheckCell.Address
Select Case Operator
Case 0, 4 'No op or Equals
If CheckCell.Value = Condition Then Passed = True
Case 1 ' Less than
If CheckCell.Value < Condition Then Passed = True
Case 2 ' Greater than
If CheckCell.Value > Condition Then Passed = True
Case 3 ' Not
If CheckCell.Value <> Condition Then Passed = True
Case 5 ' Less or Equal
If CheckCell.Value <= Condition Then Passed = True
Case 6 ' Greater or Equal
If CheckCell.Value >= Condition Then Passed = True
End Select
If Passed Then
If Not ReturnRange Is Nothing Then
Set ReturnRange = Union(ReturnRange, Range(TheColumn & CheckCell.Row))
Else
Set ReturnRange = Range(TheColumn & CheckCell.Row)
End If
End If
Next CheckCell
Set RangeIf = ReturnRange
End Function