如何使用VBA循环通过excel工作簿

时间:2016-02-03 21:23:24

标签: excel excel-vba for-loop vba

我正试图在excel工作簿中循环遍历每个工作表。我的代码只运行第一张表,但无法识别最后一行的位置。任何帮助将不胜感激。

Private Sub calculateValue()

For i = 2 To Rows.Count

    If Cells(i, 4).Value < 10 Then
        Cells(i, 6).Value = 20
    End If

    If Cells(i, 4).Value > 9 And Range("D2").Value < 40 Then
        Cells(i, 6).Value = 70
    End If

    If Cells(i, 4).Value > 39 Then
        Cells(i, 6).Value = 120
    End If


    If Cells(i, 4).Value = Empty Then Exit For

Next i

Cells(i, 6).Value = ""

End Sub

1 个答案:

答案 0 :(得分:0)

下面的第一个子代码遍历每个工作表。第二个是代码的占位符。

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call calculateValue(ws)
    Next
End Sub

Sub calculateValue(ws As Worksheet)
    'Worksheets(ws).Activate
    'iterate over cells
    'your code goes here
End Sub