VBA代码以中断模式执行,但在正常运行期间会跳到最后

时间:2018-08-26 04:38:22

标签: vba excel-vba

如果我通过在每一行中单步运行在中断模式下,则此代码将完美运行。但是,如果我正常运行它,它似乎会跳到最后。它给我一个一秒钟运行时间的消息框,并且没有代码行被执行。任何帮助将不胜感激!

Sub addVals()
Dim i As Integer, j As Integer, sheetName As String, timer As Double
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
timer = Now()
For i = 1 To 7
    sheetName = Range("sheetnames2").Offset(i, 0).Value
    For j = 1 To 3000
        If Sheets(sheetName).Range("P" & j).Value <> 0 Then
            For Each Cell In Range("R" & j, "R" & j + 30)
                If Cell = 1 Then Range("S" & j).Value = Cell.Offset(0, -17).Value: Exit For
            Next Cell
        Else
        End If
    Next j
Next i
Application.Calculation = xlCalculationAutomatic
MsgBox (Format(Now() - timer, "HH:MM:SS"))
End Sub

1 个答案:

答案 0 :(得分:1)

更正夫妇:

Date.Type

请注意此一线:

Sub addVals()

    Dim i As Integer, j As Integer, sheetName As String, timer As Double
    Dim sht As Worksheet, Cell As Range

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    timer = Now()

    For i = 1 To 7
        sheetName = Range("sheetnames2").Offset(i, 0).Value
        With Sheets(sheetName) '<< scope the loop to the correct sheet
            For j = 1 To 3000
                If .Range("P" & j).Value <> 0 Then
                    For Each Cell In .Range("R" & j).Resize(30, 1).Cells
                        If Cell.Value = 1 Then
                            .Range("S" & j).Value = Cell.Offset(0, -17).Value
                            Exit For '<< unless you really meant what you wrote?
                        End If
                    Next Cell
                End If
            Next j
        End With
    Next i

    Application.Calculation = xlCalculationAutomatic
    MsgBox (Format(Now() - timer, "HH:MM:SS"))
End Sub

与以下功能相同:

If Cell = 1 Then Range("S" & j).Value = Cell.Offset(0, -17).Value: Exit For

不同:

If Cell = 1 Then 
    Range("S" & j).Value = Cell.Offset(0, -17).Value
End If
Exit For

...因此它可能无法像您期望的那样运行