martiong
martiong

Reputation: 11

Simple VBA selection code error

I have this simple VBA code with which I want to change the background of the selected cells. Somehow the command Selection. that I learned before doesn't work. Could you help me with this code? I know the answer is probably stupid, but I can't seem to figure it out.

    Sub set_background_color()

       'Add background color to selected cells
       Selection.Interior.Color = RGB(255, 0, 0)

    End Sub

Thanks

EDIT: Sorry for the vague question, it's my first question on stack overflow so I didn't think of the importance of the type of error. It gives me the error "Compile error: Expected function or variable".

It is attached to a button, but even if I run it as a macro without button it gives me the same error.

EDIT 2: I'm running Excel 2011 on a Mac, until now it never gave me any compatibility issues in VBA. However this does not seem to work.

Upvotes: 0

Views: 277

Answers (2)

Siddharth Rout
Siddharth Rout

Reputation: 149335

If your worksheet is not protected then try this

Sub set_background_color()
    Dim r As Range

    On Error Resume Next
    Set r = Selection
    On Error GoTo 0

    If Not r Is Nothing Then
        r.Interior.ColorIndex = 3
    Else
        MsgBox "Invalid Selection"
    End If
End Sub

Upvotes: 1

Gary's Student
Gary's Student

Reputation: 96791

The problem is not within your code, it is within your cells.

Check the locked status of the cells and the protection status of the worksheet.

Upvotes: 1

Related Questions