如何循环细胞

时间:2016-05-20 17:49:14

标签: excel vba excel-vba loops

如何更新此VBA代码,以便它可以成为检查我的所有列的循环,范围从G4到G1000,并为每个列显示一个msgbox而不仅仅是G4?

Private Sub Workbook_Open()
    Dim c1 As Range
    Set c1 = ThisWorkbook.Sheets("Sheet1").Range("G4")
    If IsDate(c1) Then
    If Now >= c1 + 60 Then
        MsgBox "The Date in Sheet 1 Cell B4 has been reached or passed."
        End If
    End If
End Sub

3 个答案:

答案 0 :(得分:1)

也许:

Private Sub Workbook_Open()
    Dim c1 As Range, r As Range
    Set c1 = ThisWorkbook.Sheets("Sheet1").Range("G4:G100")
    For Each r In c1
        If IsDate(r.Value) Then
            If Now >= r.Value + 60 Then
                MsgBox "warning cell " & r.Address(0, 0) & " is expired"
            End If
        End If
    Next r
End Sub

答案 1 :(得分:0)

使用r.offset(0,-5)将引用B列

Private Sub Workbook_Open()
        Dim c1 As Range, r As Range
        Set c1 = ThisWorkbook.Sheets("Sheet1").Range("G4:G100")
        For Each r In c1
            If IsDate(r.Value) Then
                If Now >= r.Value + 60 Then
                    MsgBox "warning cell " & r.Address(0, 0) & " is expired: Value: " & r.offset(0,-5) 'r.offset(0,-5) will return the content on col
                End If
            End If
        Next r
    End Sub

希望这有帮助。

答案 2 :(得分:-1)

我相信你可以使用它:https://msdn.microsoft.com/en-us/library/office/aa221353%28v=office.11%29.aspx

For Each c1 In Worksheets("Sheet1").Range("G4:G1000").Cells
    ' copy paste your code here
Next