具有标准的总和列的宏意外停止

时间:2017-07-10 14:44:33

标签: excel excel-vba vba

我希望通过VBA计算列的总和。 这是我的代码:

Sub CALRU()
       ECP_CA = 0
       Radome_CA = 0
            For i = 1 To 21726
                If Cells(i, "L") = "GET" Then
                    If Cells(i, "H") = "2014" Then
                        ECP_CA = ECP_CA + Cells(i, "J")
                    Else
                        MsgBox "not found"
                    End If
                Else
                    MsgBox "not found"
                End If
            Next i

End Sub

我找到第一个结果的循环是真的,它是stoped.And不定义列的其余部分。 有人,可以给我一个建议,问题出在哪里? 谢谢。

2 个答案:

答案 0 :(得分:2)

如果代码停止,则必须单击MsgBox中的确定按钮才能继续宏。

修改#1:

这可能有助于解决您的问题:

Sub CALRU()
       ECP_CA = 0
       Radome_CA = 0
            For i = 1 To 21726
                If Cells(i, "L") = "GET" Then
                    If Cells(i, "H") = "2014" Then
                        ECP_CA = ECP_CA + ReturnNumber(Cells(i, "J"))
                    Else
                        MsgBox "not found"
                    End If
                Else
                    MsgBox "not found"
                End If
            Next i

End Sub

Public Function ReturnNumber(v As Variant) As Double
    Dim L As Long, temp As String, CH As String
    L = Len(v)
    If L = 0 Then
        ReturnNumber = 0
    Exit Function
End If
    temp = ""
    For i = 1 To L
        CH = Mid(v, i, 1)
        If CH Like "[0-9]" Or CH = "." Or CH = "-" Then temp = temp & CH
    Next i
    If temp = "" Then
        ReturnNumber = 0
    Else
        ReturnNumber = CDbl(temp)
    End If

End Function

答案 1 :(得分:0)

现在应该可以了:

Option Explicit

Sub CALRU()

    Dim ecp_ca          As Double
    Dim Radome_CA       As Double
    Dim i               As Long

    ecp_ca = 0
    Radome_CA = 0

    With ActiveSheet
        For i = 1 To 217
            If .Cells(i, "L") = "GET" Then
                If .Cells(i, "H") = "2014" Then
                    ecp_ca = ecp_ca + .Cells(i, "J")
                Else
                    Debug.Print "not found"
                End If
            Else
                Debug.Print "not found"
            End If
        Next i

    End With

End Sub

我已经尝试了217,因为我不想等到打印21K。我已将MsgBoxes更改为Debug.Print,并且我添加了With ActiveSheet,因为这也是一个问题。还添加了Option Explicit