我对VBA很陌生,到目前为止我的功能几乎所有东西都运行良好;它选择单元格范围“计数”,“数据”,“理想xS”作为输入,以及常量“alpha”和“C”,理想情况下将采用“idealxS”并将它们转换为“idealxs”--->“ newidealxs“使用for循环中的公式,然后它将采用转换后的”newidealxS“和”count“并对差异的平方求和。
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”时出现错误,我不知道如何正确声明范围对象或其他内容,或者可能是因为我没有索引创建的范围正确。代码的每个其他部分都有效。我不需要将单元格值存储在somwhere中,我需要它们是虚拟垃圾变量,在你知道的函数的迭代之后被抛出,比如avg和stdv,但似乎当我尝试拥有某些东西时就像那个范围它不起作用,所以我不确定范围是否也能像那样工作,或者我是否应该定义一个新数组(但是我不能使用SumXMY2命令)。我对VBA一无所知,所以请尽可能明确!
答案 0 :(得分:0)
您应该考虑使用数组而不是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