鉴于您想要最有效的方法,您可以尝试这种避免缓慢范围循环的方法
- 通过公式 chichi 循环
SpecialCells
包含错误(根据其他解决方案)
- 用于
Find
检测特定公式,而不是通过 (1) 中的每个单元格进行简单循环
此代码使用该R1C1
方法输入,Find
因此代码在必要时更改此Application
设置(然后在最后返回)
我建议您记录您希望找到的公式,然后将其输入。R1C1
符号的最大优点是它与实际的行和列位置无关。
例如在A1
符号中的一个公式
- =SUM(A1:A4) in
A5
需要对SUM(B1:B4) in
B5进行不同的搜索
- 在
R1C1
这=SUM(R[-4]C:R[-1]C)
两种情况下
代码
Sub Demo()
Dim ws As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim strAddress As String
Dim bRefSTyle
If Application.ReferenceStyle = xlA1 Then
Application.ReferenceStyle = xlR1C1
bRefSTyle = True
End If
For Each ws In ActiveWorkbook.Worksheets
Set rng1 = Nothing
On Error Resume Next
Set rng1 = ws.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If rng1 Is Nothing Then
Debug.Print ws.Name & ": No Formulae errors"
Else
'search errors for particular formula
'this sample looks for a formula which SUMS the four cells directly above it
Set rng2 = rng1.Find("=SUM(R[-4]C:R[-1]C)", , xlFormulas, xlWhole)
If Not rng2 Is Nothing Then
strAddress = rng2.Address
Set rng3 = rng2
Do
Set rng2 = rng1.Find("=SUM(R[-4]C:R[-1]C)", rng2, xlFormulas, xlWhole)
Set rng3 = Union(rng2, rng3)
Loop While strAddress <> rng2.Address
Debug.Print ws.Name & ": " & rng3.Address
Else
Debug.Print ws.Name & ": error cells, but no formulae match"
End If
End If
Next
'restore styles if necessary
If bRefSTyle Then Application.ReferenceStyle = xlA1
End Sub