VBA循环错误

我在Excel中编写VBA相对比较新。 在Excel工作表中,我在多个列中有单行的事件。 这些事件只是由它们的颜色来表示(除了它们是空白单元格)。 想象一下,将单元格A1到G1着色为红色,H1到V1着色为蓝色。

我正在尝试编写一个小程序,告诉我单元格何时改变颜色。 用我目前的代码,在下面的文本中,Excel停止响应,并且popup错误代码“运行时错误”-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 

你的ActiveCell永远不会改变。 我想你想循环通过单元格,只是testing你发现的单元格颜色是不同的单元格在同一行,但只有一列以上的单元格颜色。 像这样

 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 

我猜你会想用一些有用的东西来replaceMsgBox("color changes") ,告诉你颜色变化发生的地方,比如MsgBox("Column " & i + 1 & " had a change of color from the column immediately to the left of it.")

你的单元格引用可以做一些小小的工作,通常select一些东西是不好的。 您还需要在每次移动范围a下的代码中移动范围。 尝试这个:

 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