满足特定条件的单元格字符串的总和

时间:2018-10-23 11:37:44

标签: excel vba excel-vba sum conditional

我只是想知道如何在vba中进行计算:
如果是,则计算第一笔金额,如果不是,则不计算金额。想象一下,有四个单元格:

(cell 1) abcbc bcbcbcb cbcbcbc $1000/kskskksks/$2000//1222/1221/11/yes  
(cell 2) any words will be here $2300/heyhey hey/ //3232//3232/no  
(cell 3) kakjsak  dsdsk kdjskj 2323/ $23232/hhehe 22/33/333/yes  
(cell 4) kakaka kjsdkj ksjskjds kdjsjkdj 11 223 222/ $1121/ $2121/yes

算法是检查是或否。然后,在每一行中找到以$开头的第一笔钱,同一行中的第二笔钱将不考虑在内。

在此示例中,该程序将考虑$1000,因为它是,因此不执行第二行。并且第三个单元格将使用第一笔钱(第一个$)$23232。因此,该程序将得出$1000+$23232+$1121=$25353

3 个答案:

答案 0 :(得分:2)

考虑到您正在使用第一列放置每个值并且工作表的名称为“ Sheet1”,因此我想这就是您想要的

Sub SumFirstAmountIfYes()

    Dim AmountSum As Variant ' Declares the AmountSum

    lastRow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row ' Finds the last used row on the first column

    For i = 1 To lastRow ' Iterates over the rows to the last row
        StringValue = Sheets("Sheet1").Cells(i, 1).Value2 ' Gets the value to a variable
        If StringValue Like "*yes" Then ' Checks if the string terminates with "yes"
            FirstDollar = InStr(StringValue, "$") ' Finds first dollar symbol "$"
            FirstSlashAfterDollar = InStr(FirstDollar, StringValue, "/", 0) ' Finds first slash "\" after the first dollar symbol

            FirstAmount = Mid(StringValue, FirstDollar + 1, FirstSlashAfterDollar - FirstDollar - 1) ' Gets the amount of each row

            AmountSum = AmountSum + CDec(FirstAmount) ' Adds to the sum variable each found amount
        End If
    Next

    MsgBox (AmountSum) ' Shows the final sum of the amounts

End Sub

答案 1 :(得分:0)

这将使用split分隔yes / no和InStr来定位第一个货币符号。

_token

enter image description here

答案 2 :(得分:0)

使用excel数组公式的方法稍有不同,假设您的单元格值不包含尾随空格,

enter image description here

=SUM(IF(RIGHT(A1:A4,1)="s",MID(A1:A4,SEARCH("$",A1:A4)+1,SEARCH("/",A1:A4,SEARCH("$",A1:A4))-SEARCH("$",A1:A4)-1)*1,""))