如何正确声明范围对象并正确地索引范围内容

我对VBA很陌生,到目前为止我的function几乎都能正常工作。 它将所select的单元格范围“counts”,“data”,“idealxS”作为input,以及常量“alpha”和“C”,理想地将采用“idealxS”并将其转换为“idealxs”—>“newidealxs “使用for循环中的公式,然后它将采用变换的”newidealxS“和”计数“并对差异的平方进行求和。

Public Function TERMCALCULATION(data As Range, counts As Range, idealxS As Range, alpha, C) avg = Application.WorksheetFunction.Average(data) stdv = Application.WorksheetFunction.StDev(data) siz = Application.WorksheetFunction.Count(counts) constant1 = (1 / (stdv * ((2 * 3.14159265358979) ^ (1 / 2)))) Dim newidealxS As Range For i = 1 To siz Debug.Print i term1 = ((2.71828182845905) ^ (-(((idealxS(i, 1) - avg) / stdv) ^ 2) / 2)) term2 = (1 + Application.WorksheetFunction.Erf(0, (alpha * (((idealxS(i, 1) - avg)) / (stdv * (2 ^ (1 / 2))))))) newidealxS(i, 1).Value = C * constant1 * term1 * term2 Next i Debug.Print idealxS(68) TERMCALCULATION = Application.WorksheetFunction.SumXMY2(counts, newidealxS) End Function 

真正发生的是当我尝试定义“newidealxS”,并且我不知道如何正确地声明范围对象或其他东西,或者可能是因为我没有正确编制创build的范围。 代码的其他部分都起作用。 我不需要将单元格的值存储到某个地方,我需要它们是在你知道的函数迭代之后抛出的虚拟垃圾variables,比如avg和stdv,但是似乎当我试图获得某些东西的时候就像这是一个范围它不起作用,所以我不知道如果范围甚至工作,或者如果我应该定义一个新的数组(但我不能使用SumXMY2命令)。 我绝对没有VBA的先前的知识,所以请尽可能明确!

你应该考虑使用一个数组而不是一个范围newidealxS

 Public Function TERMCALCULATION(data As Range, counts As Range, _ idealxS As Range, alpha, C) Dim avg, stdv, siz As Long, constant1, wsf, i As Long Dim term1, term2 Dim newidealxS() '<< array, not range Set wsf = Application.WorksheetFunction avg = wsf.Average(data) stdv = wsf.stdev(data) siz = wsf.Count(counts) constant1 = (1 / (stdv * ((2 * 3.14159265358979) ^ (1 / 2)))) ReDim newidealxS(1 To siz, 1 To 1) For i = 1 To siz Debug.Print i term1 = ((2.71828182845905) ^ (-(((idealxS(i, 1) - avg) / stdv) ^ 2) / 2)) term2 = (1 + wsf.Erf(0, (alpha * (((idealxS(i, 1) - avg)) / (stdv * (2 ^ (1 / 2))))))) newidealxS(i, 1) = C * constant1 * term1 * term2 '<<EDIT: removed .Value Next i Debug.Print idealxS(68) TERMCALCULATION = wsf.SumXMY2(counts, newidealxS) End Function