[英]Excel VBA: How to sum only values larger than a specific value?
I spent the whole day at work trying to figure out a solution to my problem. 我整天都在努力寻找解决问题的方法。 Most of my googleing led me to this site, so I decided to give up and ask for some help. 我的大多数googleing都把我带到了这个网站,所以我决定放弃并寻求帮助。
I have an Excel-file containing the positions of a stock portfolio. 我有一个包含股票投资组合头寸的Excel文件。 I need to figure out how to write a macro that can tell me instantly if those positions that exceed 5% of the portfolio value together exceed 40% of the portfolio value. 我需要弄清楚如何编写一个宏,可以立即告诉我那些超过投资组合价值5%的头寸是否超过投资组合价值的40%。
I have some basic understanding of VBA and I know how to select the right column, but I cannot figure out how to sum only those positions that exceed 5% (0.05). 我对VBA有一些基本的了解,我知道如何选择正确的列,但我无法弄清楚如何只对那些超过5%(0.05)的位置求和。 I've tried different If expressions but I just cant seem to get it right. 我尝试了不同的If表达式,但我似乎无法正确使用它。
Could someone please showe me the way? 有人可以告诉我的方式吗? I just need the macro to check my column and then print in a MsgBox whether the positions(>= 0.05) exceed 40% (0.40). 我只需要宏来检查我的列,然后在MsgBox中打印位置(> = 0.05)是否超过40%(0.40)。
Thank you very much! 非常感谢你!
Example Column: 示例列:
Weights
0.032
0.067
0.103
.
.
.
0.02
To build off Doug Glancy's comment, you should be able to use SUMIF for this. 为了建立Doug Glancy的评论,你应该能够使用SUMIF。 Assuming your portfolio weights are in the Range A2:A200, this will get you what you need: 假设您的投资组合权重在A2:A200范围内,这将为您提供所需:
=SUMIF(A2:A200,">=0.05")
If i have understood your question correctly, I think the below is what you want. 如果我已正确理解您的问题,我认为以下是您想要的。
Sub GetThreshold()
Dim myRng As Range
Dim pos As Double
Set myRng = ThisWorkbook.Sheets("Sheet1").Range("A2:A100")
For Each mycell In myRng
If mycell.Value >= 0.05 Then
pos = pos + mycell.Value
End If
Next
If pos > 0.4 Then
MsgBox "Position exceeds the threshold of 40%", vbCritical, "Position Break"
Else
MsgBox "Position within the threshold of 40%", vbInformation, "Position Break"
End If
End Sub
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.