Search code examples
excelvba2d-games

excel stop a user accessing a cell if background colour is black


I am trying to build a simple game (Maze) in excel 2003. I need a Macro that stops a user selecting a cell (using arrow keys) if they have a black background colour.

I cant seem to find anyway to stop this happening (regardless of the colour).

Any hints or help would be great.

Thanks.

Tom

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim x As Integer
Dim y As String
Dim z As Integer
Dim answer As Integer
Dim OldRange As Range



x = Range("AL4").Value
y = Range("AL5").Value
z = Range("AL6").Value
accessory = Range("AL7").Value

'ColorIndex 1 is Black
If Target.Cells(1, 1).Interior.ColorIndex = 1 Then
    OldRange.Select
Else
    Set OldRange = Target
End If

I have tried this: I'm confused as to where I am going wrong! In the ThisWorkbook I have added at the very top: Option Explicit Private OldRange As Range

I have then added the following to my Private Sub Worksheet_SelectionChange(ByVal Target As Range) area:

If Target.Cells(1, 1).Interior.ColorIndex = 1 Then
    OldRange.Select
Else
    Set OldRange = Target
End If

I am still getting a Debug error on the OldRange.Select line.

UPDATE I was being slow! Sorry! Working now much appreciated.

Thanks.

Tom


Solution

  • Here's a solution for you (enter this code in worksheet code block):

    Private OldRange As Range
    
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        'ColorIndex 1 is Black
        If Target.Cells(1, 1).Interior.ColorIndex = 1 Then
            OldRange.Select
        Else
            Set OldRange = Target
        End If
    End Sub