简体   繁体   中英

Excel VBA use operators <,>, >=, <= with doubles as function arguments

I posted a question a few minutes ago about this matter and decided to create a new one with the problem a little better described. So I prepared a simple worksheet:

工作表示例

On G4 (green) I placed the formula =SUMIFS(B1:B20;A1:A20;">="&E4;A1:A20;"<"&E5) and it works fine.

The cell E4 (blue) is filled by the script:

Sub Button1_Click()

    Dim SH As Worksheet: Set SH = ThisWorkbook.Sheets("Sheet1")
    Dim R1 As Range: Set R1 = SH.Range(SH.Cells(1, 1), SH.Cells(20, 1))
    Dim R2 As Range: Set R2 = SH.Range(SH.Cells(1, 2), SH.Cells(20, 2))

    Dim V1 As Double: V1 = SH.Cells(4, 5).Value
    Dim V2 As Double: V2 = SH.Cells(5, 5).Value

    SH.Cells(5, 7).FormulaR1C1 = WorksheetFunction.SumIfs(R2, R1, ">=" & V1, R1, "<" & V2)

End Sub

It's easy to see that the value should be also 18 . However it evaluates to 0 .

Another thing, when I declare V1 and V2 as longs:

    Dim V1 As Long: V1 = Int(SH.Cells(4, 5).Value)
    Dim V2 As Long: V2 = Int(SH.Cells(5, 5).Value)

the cell E4 (blue) evaluates to 17 (which is correct because there's 17 values between 44004 and 44005 ).

Does anyone know something about this? It looks like a bug to me...

From your screenshot, your decimal dot is the , .

When you concatenate a string with a number, such as in ">=" & V1 , the number is converted to string using the current locale. Your current locale has , as the decimal dot, so you end up with ">=44004,2" .

Internally Excel stores all formulas according to the en-us locale, which, among other things, uses . for the decimal dot. These are accessible via .Formula and .FormulaR1C1 properties.
The Excel interface shows you these formulas converted to your locale. These are accessible via .FormulaLocal and .FormulaR1C1Local properties.

The functions under WorksheetFunction only expect the true internal en-us arguments. When you pass ">=44004,2" as an argument, it causes the calculation to fail, because the function expected ">=44004.2" . The zero result is an indication that a filter was malformed.

So you should give it that :

= WorksheetFunction.SumIfs(R2, R1, ">=" & Str$(V1), R1, "<" & Str$(V2))

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