【发布时间】:2017-08-27 11:02:02
【问题描述】:
我正在尝试从工作表中获取数据,看看它是否与平均值有一定的标准偏差。
我收到错误“1004”消息。我猜这是因为我将 Range 设置错了,或者我误读了如何将 For Each 函数用于 Ranges。
Sub testLimit()
Dim Range As Range
Dim currCell As Range
Dim SD As Double
Dim preRange As Range
Set Range = ActiveSheet.UsedRange
SD = InputBox("What is the Standard Dev. threshold?")
For Each currCell In Range.Cells
'****(ERROR)****
preRange = WorksheetFunction.IfError(Range(currCell.Offset(-1, 0), currCell.Offset(-6, 0)), Range("A1"))
If IsError(currCell.Offset(-6, 0)) Or currCell.Offset(-6, 0).Value = "" Or WorksheetFunction.IsText(currCell.Offset(-6, 0)) Then
currCell.Interior.color = RGB(255, 255, 255)
ElseIf currCell.Value > WorksheetFunction.Average(preRange) + WorksheetFunction.StDev(preRange) * SD Then
currCell.Interior.color = RGB(105, 255, 105)
ElseIf currCell.Value < WorksheetFunction.Average(preRange) + WorksheetFunction.StDev(preRange) * SD Then
currCell.Interior.color = RGB(255, 105, 105)
Else
currCell.Interior.color = RGB(255, 255, 255)
End If
Next currCell
End Sub
【问题讨论】:
-
出现错误时突出显示哪一行代码?
-
永远不要使用保留字来声明变量;在
Dim Range As Range这样的情况下尤其如此。使用Dim rng As Range并根据需要更改对Range object 或rng 变量的所有后续引用。 -
preRange 需要 Set 并且完全不清楚您要如何处理工作表 IFERROR function。无论如何,IFERRROR 在 VBA 中表现不佳;使用 VBA IsError function 捕获错误。
-
如果单元格位于第 2-5 行,我想捕获一个超出范围的错误 IFERROR
-
好的,你需要一个越界捕获。我不明白
IFERROR(A2:A5, A1)是如何做到这一点的。也许查看AGGREGATE function 以避免错误。