循环在excel vba中的行并获取单元格

我需要Excel中的帮助。 我的问题是:我怎样才能得到这个循环中的每一行的单元格42? 如:

For Each r In Sheets("Sheet2").UsedRange.Rows sval = r.Cells(42) If sval = "" Then If r.Cells(6).Value <> "" And r.Cells(7).Value <> "" And r.Cells(9).Value <> "" And r.Cells(10).Value <> "" And r.Cells(11).Value <> "" And r.Cells(12).Value <> "" Then MsgBox "wtehi" r.EntireRow.Interior.ColorIndex = 0 Else MsgBox "yallow" emptyMand = "ok" r.EntireRow.Interior.ColorIndex = 6 End If End If Next 

要遍历工作表ws所有行,并为每一行获取列42上的单元格,可以这样做:

 For Each rw in ws.UsedRange.Rows cell = ws.Cells(rw.Row, 42) Next 

但是,下面的方法速度快一倍,可读性更强:

 For i = 1 to ws.UsedRange.Rows.Count cell = ws.Cells(i, 42) Next 

另一个推荐的非macros选项当然是使用条件格式,我build议这个macros的一部分:

 Dim cl As Range For Each cl In Intersect(Sheets("Sheet2").UsedRange, Sheets("Sheet2").Columns(42)) If Len(cl) = 0 Then If Application.WorksheetFunction.CountIf(Cells(cl.Row, 6).Resize(1, 5), "") <> 5 Then MsgBox "wtehi" cl.EntireRow.Interior.ColorIndex = 0 Else MsgBox "yallow" emptyMand = "ok" cl.EntireRow.Interior.ColorIndex = 6 End If End If Next cl