简体   繁体   中英

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.

I have an Excel-file containing the positions of a stock portfolio. 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.

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). I've tried different If expressions but I just cant seem to get it right.

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).

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. Assuming your portfolio weights are in the Range A2:A200, this will get you what you need:

=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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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