从for循环回到if语句vba

时间:2016-05-25 00:52:32

标签: vba loops if-statement for-loop exit

我正在尝试执行一个操作,该操作将查看范围内的日期(dateRng)是否小于今天的日期,然后,如果是,则执行for循环以隐藏行w.here中的值是零。 (我正在偿还贷款,而且每个月我都希望它隐藏任何已经还清的贷款。)几个月是列,贷款是行。贷款余额为(i,j)。

问题是它永远不会退出for循环,回过头来检查每个新'j'(列)之后的日期。它只是停留在for循环中。我试过休息,退出,继续等等。似乎没有工作,至少我放置它们。如何检查日期,与'今天'进行比较,然后运行for循环检查列中的每个单元格,然后转到第2列,检查日期并执行相同的for循环。

让它变得动态是件好事,但这不是必需的,因为每个月我都可以改变代码中的范围。这完全是我个人使用的。任何帮助表示赞赏。谢谢。

Sub hidePaid()

Dim day As Range, loanRng As Range, loanSum As Worksheet, dateRng As Range, cel2 As Range, i As Long, j As Long, col As Range

Set loanSum = ThisWorkbook.Worksheets("Loan Sum")
loanSum.Activate

Set dateRng = ActiveSheet.Range("D2:R2")
Set loanRng = ActiveSheet.Range("D4:R16")

For Each day In dateRng

If day.Value < Date Then

    For j = 1 To loanRng.Columns.Count
    For i = 1 To loanRng.Rows.Count

        If loanRng.Cells(i, j).Value < 1 Then
               loanRng.Cells(i, j).EntireRow.Hidden = True
        End If

    Next i
    Next j



End If

Next
End sub

1 个答案:

答案 0 :(得分:0)

我在代码中添加了注释以显示我的更改。

你很亲密,但有一对多的循环,就像你说的那样,需要找到合适的出口。

Sub hidePaid()
Dim day     As Range
Dim loanRng As Range
Dim loanSum As Worksheet
Dim dateRng As Range
Dim i       As Long

Set loanSum = ThisWorkbook.Worksheets("Loan Sum")
loanSum.Activate

Set dateRng = ActiveSheet.Range("D2:R2")
Set loanRng = ActiveSheet.Range("D4:R16")

'This loop processes by column
For Each day In dateRng

    'Once the date in the column is greater than today, it will stop processing
    'It assumes the values in dateRng are valid dates
    '(I.e. '01/01/2016' not just 'Jan', you can use number format in Excel to
    'get a date to show as 'Jan' if that is better for you)
    If DateDiff("d", Now(), day.Value) > 0 Then Exit For

    'The line of code you had should have worked in sense,
    'it would have touched every column but only procesed those before today
    'It also assumes that value in the cell to be an actual date
    'If day.Value < Date Then

    'You do not need a column loop here as you are already in one in the
    'previous loop
    'For j = 1 To loanRng.Columns.Count

    'This loop processes all the rows that are not already hidden and if
    'the value is equal to 0 then it hides the row
    'Note: you had the check to be less than 1, .50 is less than 1 and you don't
    'want to get caught out on a loan!
    For i = 1 To loanRng.Rows.Count

        If (loanRng.Cells(i, day.Column - 3).Value = 0) And (loanRng.Cells(i, day.Column - 3).EntireRow.Hidden = False) Then
            loanRng.Cells(i, day.Column - 3).EntireRow.Hidden = True
        End If

    Next i

Next

'Its good practice to clear out resources when finishing
Set dateRng = Nothing
Set loanRng = Nothing
Set loanSum = Nothing

End Sub