【问题标题】:How to fix 'End if without block if' if there is only 1 if and 1 end if?如果只有 1 个 if 和 1 个 end if,如何解决“如果没有阻塞则结束”?
【发布时间】:2019-05-06 13:38:40
【问题描述】:

如果我在 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 相加。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    你错过了下一个单位行:

    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

    【讨论】:

    • Damian 在你发布答案的第二部分之前,我发布了几乎相同的答案,所以我会删除我的。
    • 好吧,我刚刚编辑了将计数器添加到声明中,这是我从你那里看到的,但答案已经发布了:P
    • 嗨达米安,首先非常感谢您的提示/答案。如果不进入它上面的子函数,我就不能包含 Option Explicit。
    • Option Explicit 位于模块顶部的所有代码之上。
    猜你喜欢
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多