我对VBA很新,我完全被难倒了。我有A2:A40
范围内的一系列值(销售额)。我需要它,以便要求用户输入2个阈值,假设threshold1 <= threshold2。然后让它在列表中向下移动并计算介于threshold1和threshold2之间的销售值,包括在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 & ""
答案 0 :(得分:1)
这适用于您要做的事情。但是,在您的问题中,您说您的值在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