是什么导致我的宏跳过整个循环部分?

时间:2017-05-04 01:12:29

标签: excel-vba vba excel

我们当前的系统for声明非常手动。它位于Excel工作簿中,从会计系统中提取数据。为了自动化,我创建了以下宏:

  • TableRefresh.Refresh - 刷新sheets("Aged Balances")上的数据透视表(表1)

  • Lines.StatementLines - 这会为语句提供必要的行

  • PDFEmail.EmailPDF - 如果Range("I6")Email,则会将该语句作为PDF附加到电子邮件中并发送给

  • StatementPrint.PrintStatement - 如果Range("I6")Email,则会打印准备发布的对帐单

  • DB2Clear.ClearDB2 - 清除为下一个客户信息准备好的对帐单

现在我正在尝试创建一个将所有这些组合在一起的宏。表1(如上所述)包含所有客户及其客户代码(第1列),需要为其创建语句。这就是我目前所拥有的:

Sub Statements()
    Dim i As Integer
    Dim LastRow As Long

    With Sheets("Aged Balances")
        LastRow = .Cells(.Rows.Count, 14).End(xlUp).Row
    End With

    Call TableRefresh.Refresh

    'Now the loop begins.
    For i = 3 To LastRow

    'Now set the new Client Code
    Worksheets("Statement").Range("K3").Value = Worksheets("Aged 
    Balances").Cells(i, 1).Value

    Call Lines.StatementLines

        If Sheets("Statements").Range("I6").Value = "Email" Then
            Call PDFEmail.EmailPDF
        ElseIf Sheets("Statements").Range("I6").Value = "Print" Then
            Call StatementPrint.PrintStatement
        Else
            Return
        End If

        MsgBox "Statement Complete", vbInformation
        Call DB2Clear.ClearDB2
    Next i

    MsgBox "Statements Complete", vbInformation    
End Sub

当使用F8步进方法时,我注意到它到达循环部分的第一行(For i = 3 To LastRow)然后完全跳过整个循环部分并转到消息框。

提前感谢您的帮助和建议。最受赞赏的。

1 个答案:

答案 0 :(得分:0)

以下是最终代码:

Sub Statements()
Dim i As Integer
Dim lastRow As Long

'This was where I was having issues. Because the table sometimes had less than 3 rows it was skipping the loop.
        With Sheets("Aged Balances")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
        End With

        Call TableRefresh.Refresh

        'Now the loop begins.
        For i = 3 To lastRow

        Worksheets("Statement").Range("K3").Value = Worksheets("Aged Balances").Cells(i, 1).Value

'Because I changed the code above it no longer takes into account that it is a Pivot Table so I have put in this If statement so that it doesn't include the last two lines of the table(blank and Grand Total).
        If Sheets("Statement").Range("I6").Value = "" Then
        Exit For

        ElseIf Worksheets("Statement").Range("I6").Value = "Email" Then
        Call Lines.StatementLines
        Call PDFEmail.EmailPDF

        ElseIf Sheets("Statement").Range("I6").Value = "Post" Then
        Call Lines.StatementLines
        Call StatementPrint.PrintStatement

        End If

        Call DB2Clear.ClearDB2

Next i

     MsgBox "Statements Complete", vbInformation

End Sub

感谢@Peh和@DavidZemens的评论让我得到了这个。似乎它们是正确的,因为它在To LastRow小于3时跳过循环。请参阅代码中的注释。

现在我已经有更多时间从事其他自动化工作了!