如何遍历VBA和Excel中选定列中的每个单元格?

时间:2017-06-21 07:58:46

标签: excel vba excel-vba

我想在选择中计算每天(列)的颜色。如何遍历所选列中的每个单元格?我已经实现了颜色检查代码。

示例:

输出继电器:

  • 第15天有8个紫色和3个绿色
  • 第16天有8个紫色和1个绿色

依旧......

enter image description here

4 个答案:

答案 0 :(得分:2)

Sub test()
    Dim purpleCounter As Long, greenCounter As Long
    Dim c As Range, r As Range

    ' For each column in the selected area
    For Each c In Selection.Columns
        ' Reset the color counters
        purpleCounter = 0
        greenCounter = 0

        ' For each row (=cell) in the column we're working on cf. the previous loop
        For Each r In c.Rows
            ' If color of the cell matches our value, increment the respective counter
            If r.Interior.Color = 10498160 Then purpleCounter = purpleCounter + 1
            If r.Interior.Color = 7658646 Then greenCounter = greenCounter + 1
        Next r

        ' Print the results to the Immediate window - or replace this section with whatever
        Debug.Print "Day " & c.Rows.Item(1).Value & " has " & purpleCounter & _
            " purple and " & greenCounter & " green."
    Next c
End Sub

enter image description here

答案 1 :(得分:1)

您还可以在完整列上使用With Application.FindFormat.Interior .color=vbRed end with set r=range("c3:c30").find(what:="*", searchformat:=True) 循环来创建计数器,进行颜色检查和计数。

例如,沿着这些方向发展。

r=range("c3:c30").find(what:="*", after:=r, searchformat:=True)

然后循环直到r为空,递增计数器。循环$(document).ready(function(){ alert("test"); $("#canvas").click(function(e){ alert("canvas"); e.stopPropagation(); }); $(".middle").click(function(){ alert("middle"); }); });

感谢。

答案 2 :(得分:0)

For Next loop

For c = 15 to 17 'check the column num
    For r = 3 to 30 'assuming your last row is 30
       'color check code here
    next r
next c

答案 3 :(得分:-3)

Dim Cell as Range
For Each Cell in Selection 
    If cell.row = ? Then ' enter code here
    If cell.Column = ? Then ? = Cell.Interior.Color
Next