【问题标题】:VBA looping errorVBA 循环错误
【发布时间】:2016-09-08 19:21:18
【问题描述】:

我对在 Excel 中编写 VBA 比较陌生。在 Excel 工作表中,我在多列的单行中发生了事件。这些事件仅由它们的颜色表示(除了它们是空白单元格)。想象一下,将单元格 A1 到 G1 涂成红色,将 H1 到 V1 涂成蓝色。

我正在尝试编写一个子程序来告诉我单元格何时改变颜色。使用我当前的代码,在下面的文本中,Excel 停止响应并弹出错误代码“运行时错误'-2147417848 (80010108)'”。我不确定问题出在哪里。

Sub colorReader()

    Set a = ActiveCell

    Range("C8").Select

    Dim cellColor As String
    cellColor = ActiveCell.Interior.Color
    MsgBox (cellColor)

    Do While cellColor = "13408767"
        a = ActiveCell.Offset(, 1)
        If cellColor <> "13408767" Then
            MsgBox ("end color")
        End If
    Loop

End Sub

【问题讨论】:

    标签: vba excel loops


    【解决方案1】:

    您的ActiveCell 永远不会改变。我想您想遍历单元格并测试您找到的单元格颜色是否与同一行中单元格的单元格颜色不同但仅超过一列。像这样

    for i= 3 to 100 'or whatever your last column number happens to be
        'This tests to see if the interior color of a cell is different from
        'the on in the same row but the next column over
        if cells(8, i).Interior.ColorIndex <> cells(8, i+1).Interior.ColorIndex then
            MsgBox("color changes")
        end if
    next i
    

    我猜你会想用一些有用的东西替换MsgBox("color changes"),它告诉你颜色变化发生在哪里,比如MsgBox("Column " &amp; i + 1 &amp; " had a change of color from the column immediately to the left of it.")

    【讨论】:

    • 谢谢!是的,我要更改 MsgBox,我只是将其用作检查点,以确保代码在继续之前正常工作。
    【解决方案2】:

    您的单元格引用可以做一些工作,通常认为 .select 某些东西是不好的。您还需要移动范围,在范围下方的代码中,每次都会移动范围。试试这个:

    Sub colorReader()
    dim a as range
    Set a = activeworksheet.Range("C8")
    
    
    Dim cellColor As String
    cellColor = ActiveCell.Interior.Color
    MsgBox (cellColor)
    
    Do While cellColor = "13408767"
        a = a.Offset(, 1)
        If cellColor <> "13408767" Then
            MsgBox ("end color")
        End If
    Loop
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 2013-07-02
      • 2018-02-13
      • 2011-11-30
      • 2019-01-07
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多