2015-07-20 149 views
0

我以編程方式創建Excel工作簿,並將宏關聯到按鈕,此宏應檢查用戶在工作表中輸入的值是否正確併爲根據情況綠色或紅色的細胞。運行時錯誤1004「Interior.Color」

宏的代碼是在另一個Excel工作簿,並加入到與此代碼創建的工作簿:

With newWorkBook.Worksheets(1).Buttons.Add(350, 115, 50, 41.25) 
    .Caption = "Vérifier la conformité" 
    .OnAction = "'" & ThisWorkbook.FullName & "'!check_FCM" 
End With 

下面是宏的代碼部分不工作:

For i = 0 To col - 1 
    If (IsNumeric(Cells(29, i + 2).Value)) Then 
     If (Cells(29, i + 2).Value >= Cells(31, i + 2).Value And Cells(29, i + 2).Value <= Cells(32, i + 2)) Then 
      Range(Cells(29, i + 2).Address()).Interior.Color = RGB(0, 255, 0) 
     Else 
      Range(Cells(29, i + 2).Address()).Interior.Color = RGB(255, 0, 0) 
      isCorrect = False ' 
     End If ' 
    End If ' 
Next i ' 

的問題似乎來自使用「Interior.Color=RGB(x,y,z)」,因爲當我刪除它時,我沒有收到錯誤。

+1

工作表是否受到保護?順便說一句,可以使用:'將細胞(29,I + 2)= .Interior.Color RGB(0,255,0)'而不是'範圍(將細胞(29,I + 2)。地址())內部。顏色爲RGB(0,255,0)' – Rory

+0

是,紙張被保護的,當我刪除保護它工作正常,但我需要保持保護工作表,我該如何使宏觀調控工作? – otus

+0

您需要在應用新顏色之前關閉保護並將其打開。或者您可以更改保護級別以允許更改單元格顏色。 – mielk

回答

1

可以撤消保護表如下:

Sheets("sheetname").Unprotect 

For i = 0 To col - 1 

    If (IsNumeric(Cells(29, i + 2).Value)) Then 

     If (Cells(29, i + 2).Value >= Cells(31, i + 2).Value And Cells(29, i + 2).Value <= Cells(32, i + 2)) Then 
      Cells(29, i + 2).Interior.Color = RGB(0, 255, 0) 
     Else 
      Cells(29, i + 2).Interior.Color = RGB(255, 0, 0) 
      isCorrect = False 
     End If 

    End If 

Next i 

Sheets("sheetname").Protect 

而且還可以使用細胞對象改變顏色。覈實。我對你的代碼做了小小的修改。

+0

對於任何想知道的人來說,Mac Excel 2016似乎絕對需要解除保護,而Windows Excel 2013與UserInterfaceOnly協同工作:True ... – virmaior