【问题标题】:loop on the rows in excel vba and get cell在excel vba中的行上循环并获取单元格
【发布时间】:2012-12-14 16:11:05
【问题描述】:

我需要 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

【问题讨论】:

  • 你到底是什么意思?每列的第 42 行?
  • 我想为工作表中的每一个使用的行循环,并想像上面那样为每一行获取第 42 列的单元格和值,我想看看列的值是空的然后想查看单元格 6 7 9 10 11 12 是否为空,然后将行的颜色设为白色,否则将其设为黄色

标签: excel vba


【解决方案1】:

要遍历工作表 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

【讨论】:

  • cell 变量是一个对象引用,因此在赋值过程中必须使用Set 语句,否则会抛出this 错误。了解更多Set关键字here
  • @RBT 如果 OP 想要将单元格引用为 Range 对象,那么您是对的,但他想引用该值,所以在这种情况下 cell = ws.Cells(i, 42).Value 会澄清它。
【解决方案2】:

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

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

【讨论】:

  • 已解决,我知道如何通过 Cells(rowVariable.Row, 42) 获取循环中每个单元格的单元格。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
相关资源
最近更新 更多