【问题标题】:total = total + ActiveCell.Value not working in a for each looptotal = total + ActiveCell.Value 不适用于每个循环
【发布时间】:2013-09-02 18:04:35
【问题描述】:

我有这段代码,我想在另一个工作表中查找一些单元格,如果它们符合条件,则将相邻单元格添加到总数中,然后返回到调用单元格函数的总数中。

Function collectUtfall(A1 As String, Ax As String)
Dim rng As Range
Dim total As Long: total = 0

Set rng = Sheets("Utfall").Range("M2:O272")

Dim cell As Range

For Each cell In rng
    If StrComp(cell.Offset(0, 1).Text, Ax, vbTextCompare) = 0 Then
        total = total + ActiveCell.Value
    Else

    End If
Next

collectUtfall = total

End Function

问题是我在执行时收到“循环引用”错误。这样使用ActiveCell.Value有问题吗?

如果我只是尝试一个值,比如 10,它就可以正常工作:

total = total + 10

所以问题出在ActiveCell.Value

【问题讨论】:

  • 您不应将此函数与ActiveCell 一起使用,因为 ActiveCell 始终是您在此函数中键入的单元格。
  • 使用总计 = total + cell.Value
  • 是的,谢谢你,这很容易解决!
  • 您的 UDF 存在一些其他问题,我建议您解决这些问题 - 1) 您的编码函数需要变得易变,因为它引用了不在 UDF 参数中的单元格。 2) 引用 cell.Text 是危险的,因为引用的单元格可能会返回 #### 等 3) 你不需要 OFFSET,只需将“M2:O272”更改为“O2:P272”
  • @mehow :使用 .TEXT 的理由很少:请参阅 fastexcel.wordpress.com/2011/11/30/… 99.9% 的时间用户最好避免使用 .Text,我在 OP 帖子中没有看到任何可以证明的内容它

标签: performance excel vba for-loop foreach


【解决方案1】:
Function collectUtfall(A1 As String, Ax As String)

Dim rng As Range

Dim total As Long


set total = 0


Set rng = Sheets("Utfall").Range("M2:O272")


Dim cell As Range


For Each cell In rng

    If StrComp(cell.Offset(0, 1).Text, Ax, vbTextCompare) = 0 Then
        total = total + Cell.Value

    Else


    End If

Next Cell


collectUtfall = total


End Function

【讨论】:

    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多