【问题标题】:WorksheetFunction IFERROR generates Error 1004WorksheetFunction IFERROR 生成错误 1004
【发布时间】: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 objectrng 变量的所有后续引用。
  • preRange 需要 Set 并且完全不清楚您要如何处理工作表 IFERROR function。无论如何,IFERRROR 在 VBA 中表现不佳;使用 VBA IsError function 捕获错误。
  • 如果单元格位于第 2-5 行,我想捕获一个超出范围的错误 IFERROR
  • 好的,你需要一个越界捕获。我不明白IFERROR(A2:A5, A1) 是如何做到这一点的。也许查看AGGREGATE function 以避免错误。

标签: excel vba


【解决方案1】:

您正在尝试将WorksheetFunction.IfError 函数的结果传递给Range 对象:

preRange = WorksheetFunction.IfError(Range(currCell.Offset(-1, 0), currCell.Offset(-6, 0)), Range("A1"))

IfError 函数返回单元格的值,而不是对单元格的引用。替换为:

Dim testCell As Range
Dim theUsedRange As Range

    Set theUsedRange = ActiveSheet.UsedRange

    SD = InputBox("What is the Standard Dev. threshold?")
    For Each currCell In theUsedRange.Cells
        Set preRange = ActiveSheet.Range(currCell.Offset(-1, 0), currCell.Offset(-6, 0))
        For Each testCell In preRange.Cells
            If IsError(testCell) Then
                Set preRange = ActiveSheet.Range("A1")
                ' Found an error, no need to check the rest of the cells
                Exit For
            End If
        Next testCell
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多