简体   繁体   中英

Run time error 1004 “Interior.Color”

I'm programmatically creating Excel workbooks, with a macro associated to a button, this macro is supposed to check if the values entered by the user in the worksheet are correct and to color the cells in green or red depending on the case.

The macro's code is in another Excel workbook and is added to the created workbooks with this code :

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

Here is the macro's code part that doesn't work :

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 '

The problem seems to be coming from the use of " Interior.Color=RGB(x,y,z) " because when I remove it I don't get a bug.

You can Unprotect and Protect sheet as follow:

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

And also can use Cells object to change color. Check it. I made small modification to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM