简体   繁体   中英

Use “sumif” with “.formula” and variables in VBA

I need to iterate the "condition" in the formula "sumif". The variable type is "string" but my code doesn´t work. I can´t keep the condition of the string of the variable. The code is an example if i can solve the problem with the "variable". I just need to simply iterate that variable. The code is:

Private Sub cmd_psps_Click()

Dim prueba As Integer
Dim var As String
prueba = Sheets("PRUEBAS").Index

var = "a"
Sheets(prueba).Cells(5, 16).Formula = "=sumif(" & Range(Cells(4, 13), 
Cells(8, 13)).Address() & "," & var & "," & Range(Cells(4, 14), Cells(8, 
14)).Address() & ")"
End Sub

The problem is in ," & var & ", with that code the cell in worksheet looks like:

=SUMAR.SI($M$4:$M$8;a;$N$4:$N$8)

But I need:

=SUMAR.SI($M$4:$M$8;"a";$N$4:$N$8)

I can use the condition with a simpletext for example "a". But I need to iterate the condition with a variable.

Not strictly an answer, but for the code readability, when using manual Excel's formula construction, it's good to have handy function to concatenate strings:

Function FormatString(s As String, ParamArray args() As Variant)
    Dim x%
    For x = LBound(args) To UBound(args)
        s = Replace$(s, "{" & x & "}", args(x))
    Next
    FormatString = s
End Function

The usage:

Sub G()
    MsgBox FormatString("I have {0} apples and {1} oranges", 10, 20)
End Sub

You use placeholders {0} , {1} etc. for parameters. This is like what C#'s String.Format does.

Thus, your formula will look like this:

Sub G()

    Dim sFormula$
    Dim var$
    var = "A1"

    sFormula = FormatString( _
        "=SUM({0},{1},{2})", _
        Range(Cells(4, 13), Cells(8, 13)).Address(), _
        var, _
        Range(Cells(4, 14), Cells(8, 14)).Address())

End Sub

Now the code looks more readable.

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