2016-09-08 155 views
0

我在Excel中編寫VBA相對比較新。在Excel工作表中,我有一些列中出現單行的事件。這些事件只是由它們的顏色來表示(除了它們是空白單元格)。想象一下,將單元格A1到G1着色爲紅色,H1到V1着色爲藍色。VBA循環錯誤

我想寫一個子,告訴我什麼時候單元格改變顏色。用我目前的代碼,在下面的文本中,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 

回答

2

您的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("Column " & i + 1 & " had a change of color from the column immediately to the left of it.")東西來取代MsgBox("color changes")

+0

謝謝!是的,我要更改MsgBox,我只是用它作爲檢查點,以確保代碼在我繼續之前正常工作。 – Andrew

+0

不客氣。很高興我能幫上忙。 –

0

您的單元格引用可能會做一些小工作,通常認爲選擇不了。您還需要在每次移動範圍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