2017-02-09 8 views
2

私はVBAにとって非常に新しく、完全に困惑しています。私はA2:A40の範囲の値(販売)の範囲を持っています。私は、threshold1を仮定して2つのしきい値を入力するようユーザーに要求する必要があります。< = threshold2。次に、リスト内を下に移動させ、threshold1とthreshold2の間の売上値を数えます(結果をmsgboxに表示します)。今すぐサブボックスを実行するとmsgboxにSalesが0として表示されます。VBA:2つの数値の間にある値を合計するMsgboxループ

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 & "" 
+1

これは、 'InputBox'や' MsgBox'よりもカスタム 'UserForm'に適しています。 3つの別々のポップアップのUXは恐ろしいです。 – Comintern

+4

または単に入力用に2つのセルを使用し、合計にSUMIFS()を使用します。 –

+1

変数threshold1とthreshold2は整数ですが、文字列引用符( ")で囲んではいけません。引用符を取り除いてから&を削除してください。 –

答えて

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 
+1

しきい値変数の検証を追加する必要があります。 threshold2より大きい、私は合計が働かないと思う –

+1

@Diego Ribbaええそれは非常に良いキャッチです。 –

関連する問題