excel 达到某个值之前的列总和

w3nuxt5m  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(132)

| T的|产品|Rs|值| 180000 |
| --|--|--|--|--|
| TT/21-22/079| PROD/21-22/00064| RS27C150X75X6.5X10JR | 1718 ||
| TT/21-22/079| PROD/23-24/04240| RS27C150X75X6.5X10JR | 3550 ||
| TT/21-22/079| PROD/23-24/04241| RS27C150X75X6.5X10JR | 2384 ||
| TT/21-22/079| PROD/23-24/04242| RS27C150X75X6.5X10JR | 1600 ||
| TT/21-22/079| PROD/23-24/04956| RS27C150X75X6.5X10JR | 4824 ||
| TT/21-22/079| PROD/23-24/04957| RS27C150X75X6.5X10JR | 1600 ||
| TT/21-22/079| PROD/23-24/04958| RS27C150X75X6.5X10JR | 2498 ||
| TT/21-22/079| PROD/23-24/04961| RS27C150X75X6.5X10JR | 22439 ||
| TT/21-22/079| PROD/23-24/04962| RS27C150X75X6.5X10JR | 7180 ||
| TT/21-22/079| PROD/23-24/05081| RS27C150X75X6.5X10JR | 3450 ||
| TT/21-22/079| PROD/23-24/05082| RS27C150X75X6.5X10JR | 3101 ||
我正试图写一个脚本添加到第四列的总和,直到达到总小于或等于E1,我想选择所有行,直到总小于或等于所需的值。
我运行了一个循环来计算第四列的总和,但它会出错,因为总和永远不会接近所需的值。
当E1的值小于第4列的总和时,代码运行正常。
我知道这很简单,但我试过了,没有用。

Sub test()
    Dim TempReq As Long
    Set sht = Worksheets("TempReq")
    lrD = sht.Cells(Rows.Count, 4).End(xlUp).row

    For i = 1 To lrD
        j = 1
        TempReq = TempReq + sht.Cells(i, 4).Value
        If TempReq => sht.Cells(j, 5).Value Then
            Set rng = sht.Range("a1:d" & i)
        End If
    Next i
    rng.Select
End Sub

字符串

fquxozlt

fquxozlt1#

这应该可以:

Sub test()
    Dim TempReq As Long, sht As Worksheet, lrD As Long
    Set sht = Worksheets("TempReq")
    lrD = sht.Cells(Rows.Count, 4).End(xlUp).Row
    Dim i As Long, Rng As Range, maxValue As Long
    maxValue = sht.Range("E1").Value
    For i = 2 To lrD
        TempReq = TempReq + sht.Cells(i, 4).Value
        If TempReq > maxValue Then 'went over the limit
            Set Rng = sht.Range("A2:D" & i - 1)
            Exit For
        End If
    Next i
    If Rng Is Nothing Then 'didn't reach it
        Set Rng = sht.Range("A2:D" & i - 1)
        MsgBox "Maximum never reached"
    Else
        MsgBox "Maximum reached on row " & i - 1
    End If
    Rng.Select 'try not to use Select :)
End Sub

字符串
它会通知值是否太小而无法达到限制以及最后一个值的位置。如果您不想获得MsgBox,当然可以使用Debug.Print
尝试to avoid using Select,因为你不需要使用Select来使用你的范围变量。另外,声明 * 所有 * 你的变量,使用Option Explicit来避免这种情况。

相关问题