簡體   English   中英

VBA:對兩個數字之間的值求和的 Msgbox 循環,包括

[英]VBA: Msgbox Loop that sums values that are between two numbers, inclusive

我對 VBA 很陌生,我完全被難住了。 我在A2:A40范圍內有一系列值(銷售額)。 我需要它以便要求用戶輸入 2 個閾值,假設閾值 1 <= 閾值 2。 然后讓它在列表中向下移動並計算閾值 1 和閾值 2 之間的銷售值,包括在 msgbox 中顯示結果。 現在,當我運行 sub 時,msgbox 將 Sales 顯示為 0。感謝任何幫助。

    Sheet1.Activate
Dim cell As Range
Dim sales As Range
Set sales = Sheet1.Range("B2:B40")
Dim threshold1 As Integer
Dim threshold2 As Integer
Dim sum As Integer
Dim Total As Integer

threshold1 = InputBox("Enter threshold 1", "Threshold 1")
threshold2 = InputBox("Enter threshold 2", "Threshold 2")

For Each cell In sales
    If cell.Value < " & threshold1 & " And cell.Value > " & threshold2 & " Then
        sum = sum + cell.Value
    End If
Next cell

Total = sum

MsgBox "The total sales between " & threshold1 & " and " & threshold2 & " is " & Total & ""

這將適用於您正在嘗試做的事情。 但是,在您的問題中,您說您的值在 A 列中,但您的銷售額設置為 B 列。我擁有的代碼是您的值是否在 B2:B40 中。 如果值在 A 中,那么您只需要更改它。

Sub test()

Sheet1.Activate
Dim cell As Range, sales As Range
Dim threshold1 As Integer, threshold2 As Integer, placeHolder As Integer
Dim sum As Integer, Total As Integer

Set sales = Sheet1.Range("B2:B40")

threshold1 = InputBox("Enter threshold 1", "Threshold 1")
threshold2 = InputBox("Enter threshold 2", "Threshold 2")

If threshold1 < threshold2 Then
    placeHolder = threshold1
    threshold1 = threshold2
    threshold2 = placeHolder
End If

For i = 2 To 40
    If Sheets("Sheet1").Range("B" & i).Value < threshold1 And Sheets("Sheet1").Range("B" & i).Value > threshold2 Then
        sum = sum + Sheets("Sheet1").Range("B" & i).Value
    End If
Next i

Total = sum

MsgBox "The total sales between " & threshold1 & " and " & threshold2 & " is " & Total & ""
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM