首页 > 解决方案 > 在 Excel 中将 2 个数字与 VBA 循环进行比较时强制保留三位小数

问题描述

我正在运行一个嵌套循环来比较 B 列中是否有 7 个概念性的数字都高于平均(D 列)控制限制。问题是,当我将三位小数的实际结果与两位小数的平均值进行比较时,它会将结果四舍五入到小数点后两位。我将两列都格式化为小数点后 3 位的数字。当我 Debug.Print 它将打印。

Sub seven_above_average()

Dim i As Integer, j As Integer, count As Integer
Dim lastRow As Integer
Dim result As Double, limit As Double

lastRow = Cells(Rows.count, "A").End(xlUp).Row

count = 0
For j = 12 To lastRow
    For i = j - 7 To j
        result = Cells(i, 2).Value
        limit = Cells(i, 4).Value
        If result >= limit Then
            count = count + 1
        End If
    Next i

    If count >= 7 Then
        For i = j To j - 7 Step -1
            Cells(i, 26).Value = 1
            Debug.Print ("Result = " & result)
            Debug.Print ("Limit = " & limit)
        Next i
    End If
    count = 0
Next j
End Sub

即使有 1.389 和 1.388 的结果,图片中的所有数据在第二个 If 条件下都为真。

If count >= 7 then...


一些对第二个 if 为真的数据的图片

标签: excelvba

解决方案


要扫描最后 7 个单元格,您必须使用:

For i = j - 6 To j

代替:

For i = j - 7 To j

推荐阅读