如果我在For Each语句之间有一个if语句,这会影响我需要在何处放置“ end if”以及我正在使用多少end if语句?
如果增加了更多内容,但没有帮助,我已经尝试到最后。
Sheets("Arrivals").Select
Dim cel As Range
Dim unit As Range
ParcelCount = Range("BW8").Value
LowerParcelCount = Range("BW5").Value
ThresholdCount = 0
For Each cel In Range("BQ3:BQ78")
If cel.Value > LowerParcelCount Then
For Each unit In Range("C3:C78")
ThresholdCount = ThresholdCount + unit.Value
End If
Next cel
Next unit
Range("BS16") = ThresholdCount
我希望代码能够运行。如果BQ3:BQ78范围内的单元格值符合条件,则C3:C78范围内的调用值应加到空变量ThresholdCount。
答案 0 :(得分:5)
您错过了下一个广告单元行:
Option Explicit
Sub Test()
Sheets("Arrivals").Select
Dim cel As Range
Dim unit As Range
ParcelCount = Range("BW8").Value
LowerParcelCount = Range("BW5").Value
ThresholdCount = 0
For Each cel In Range("BQ3:BQ78")
If cel.Value > LowerParcelCount Then
For Each unit In Range("C3:C78")
ThresholdCount = ThresholdCount + unit.Value
Next unit
End If
Next cel
Range("BS16") = ThresholdCount
End Sub
另外,您应该学习缩进代码,避免使用.Select
并使用Option Explicit
声明所有变量
在这里,您的代码应为:
Option Explicit
Sub Test()
Dim ws As Worksheet 'declare your worksheets
Set ws = ThisWorkbook.Sheets("Arrivals") 'like this you will refer to it using ws
Dim cel As Range, unit As Range
Dim ParcelCount As Long, LowerParcelCount As Long, ThresholdCount As Long
With ws 'you could also use With ThisWorkbook.Sheets("Arrivals") if you are not using that sheet anymore
ParcelCount = .Range("BW8").Value
LowerParcelCount = .Range("BW5").Value
ThresholdCount = 0
For Each cel In .Range("BQ3:BQ78")
If cel.Value > LowerParcelCount Then
For Each unit In .Range("C3:C78")
ThresholdCount = ThresholdCount + unit.Value
Next unit
End If
Next cel
.Range("BS16") = ThresholdCount
End With
End Sub
如您所见,由于我们都在表格顶部声明了该表格并一直使用它作为引用,因此无需选择表格到达的位置,因为所有内容都在With ws