VBA Range.value函数导致意外结束

VBA Range.value函数导致意外结束,vba,excel,Vba,Excel,这似乎是一个非常简单的问题,但我无法理解为什么我的函数在Range.value=val调用中意外结束。也许我遗漏了一些非常基本的东西,但我已经测试过了,它们中的每一个都无法解决任何问题,我不知道如何捕捉错误 以下是初始函数: Function incrementCount(upper As Range, Summed As Range, ParamArray sums() As Variant) Dim deduct As Integer Dim summation As Integer Di

这似乎是一个非常简单的问题,但我无法理解为什么我的函数在Range.value=val调用中意外结束。也许我遗漏了一些非常基本的东西,但我已经测试过了,它们中的每一个都无法解决任何问题,我不知道如何捕捉错误

以下是初始函数:

Function incrementCount(upper As Range, Summed As Range, ParamArray sums() As Variant)

Dim deduct As Integer
Dim summation As Integer
Dim elem As Variant
Dim i As Long
Dim temp As Range
up = upper.Value
summation = Summed.Value
'Initialize the starting points of the increments
For i = LBound(sums) To UBound(sums)
    MsgBox IsObject(sums(i)) 'Prints out as an true
    MsgBox TypeName(sums(i)) 'Prints out as Rnage
    MsgBox sums(i).Value 'Prints out as 0
    Set temp = sums(i) 
    MsgBox temp.Value 'Prints out as 0
    Set temp = Summed
    MsgBox temp.Value 'Prints out as 1 (which is correct)
    temp.value = 3 'Errors here
    MsgBox temp.Value 'Never makes it to this line
    sums(i).Value = 1 'I have also tried this with the same result
Next i

<more code that is never reached>

End Function

最终,我希望能够做一些类似于中讨论的事情,我在一个随机的范围分类上循环,并将它们增加。任何帮助都将不胜感激。

您尚未指定如何调用IncrementCount()


如果您的函数是从工作表单元格中调用的,那么它将在正确的行中“爆炸”。从单元格调用的UDF不能修改其他单元格的内容,它只能返回一个值。

如果不关注代码,您能准确地告诉我们您要做什么吗?我认为这段代码对于一个简单的任务来说有点过于复杂,基于你所指的帖子。我试图找到一组值达到指定总和的最佳增量数量。也就是说,第一组是x*4,第二组是x*6,x需要是什么才能等于y(一些和)。是否有一个内置函数可以做到这一点?还应注意,x*4和x*6不在相邻的单元格中。我无法让goal seek工作,因为它不会一次增加所有目标。首先,我支持@David Zemens在下面的评论中说它应该是一个子程序。第二,为什么不为此使用解算器?如果这是您需要的优化场景,我建议使用它。好的,这就是我正在尝试做的。我不知道那个事实。有没有办法改变另一个单元格值,可能是通过调用函数中的子例程?只能间接地…………您可以重新设计您的系统,让UDF向单元格返回值,并让Calculate事件宏响应计算。我可以通过子例程调用它来实现这一点。谢谢你的帮助!
Function testsub(thecell As Range, thevalue As Integer)
    thecell.value = thevalue
End Function