简体   繁体   English

VBA中的加权平均费率

[英]Weighted average rate in VBA

I am quite new to VBA so I am sorry if my question might seems very trivial.我对 VBA 很陌生,所以如果我的问题看起来很微不足道,我很抱歉。 I would love to write a function in VBA which helps to estimate weighted average rate (for loan portfolio, for instance).我很想在 VBA 中编写一个函数来帮助估计加权平均利率(例如,对于贷款组合)。 I wrote the following VBA code:我编写了以下 VBA 代码:

Function WAIRS(Amount As Range, InterestRate As Range, MatchRange As Range, Match1)
WAIRS = Evaluate("=SUMPRODUCT(--(""" & MatchRange & """ = """ & Match1 & """),""" & Amount & """, """ & InterestRate & """)")      /Application.WorksheetFunction.SumIfs(Amount, MatchRange, Match1)
End Function

The problem is that when I run this function in Excel by adding respective function criterias I get an "#VALUE#".问题是,当我通过添加相应的函数条件在 Excel 中运行此函数时,我得到一个“#VALUE#”。 I have tried a lot but cannot find out what is wrong.我尝试了很多,但无法找出问题所在。 I Would highly appreciate if you can help me.如果您能帮助我,我将不胜感激。

Thank you in advance.先感谢您。

Best, Jeyhun最好的,杰勋

The string you build for Evaluate should (in this case) not include literal double quotes.您为Evaluate构建的字符串(在本例中)不应包含文字双引号。 Instead of quoting the result of a range value而不是引用范围值的结果

"""" & MatchRange & """"

...you should retrieve the address notation of that range, and use that without wrapping it in quotes: ...您应该检索该范围的地址符号,并使用它而不用引号将其括起来:

MatchRange.Address()

If you apply that consistently, it would make the Evaluate part of the formula look like this:如果您始终如一地应用它,它会使公式的Evaluate部分看起来像这样:

"=SUMPRODUCT(--(" & MatchRange.Address() & " = " & Match1.Address() & "), " & _
                    Amount.Address() & ", " & InterestRate.Address() & ")" 

When range is another sheet:当范围是另一张纸时:

The above will not work if your ranges are on another sheet.如果您的范围在另一张纸上,则上述方法将不起作用。 In that case, I would suggest to create this function:在这种情况下,我建议创建这个函数:

Public Function fullAddr(range As Range)
    fullAddr = "'" & range.Parent.Name & "'!" & _
                  range.Address(External:=False) 
End Function

And then in your formula:然后在你的公式中:

"=SUMPRODUCT(--(" & fullAddr(MatchRange) & " = " & fullAddr(Match1) & "), " & _
                    fullAddr(Amount) & ", " & fullAddr(InterestRate) & ")" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM