0

I want to let Excel automatically change the color of a cell if that cell's value is either larger or smaller by 10% than the cell that at same row but three columns to the left.

Here is the code:

Sub testing1()
    Dim x As Integer
    Dim y As Integer

    For x = 35 To 5 Step -3
        For y = 11 To 75 Step 1
            If Cells(y, x).Value < 0.9 * Cells(y, x - 3).Value Or _
               Cells(y, x).Value > 1.1 * Cells(y, x - 3) Then
                Cells(y, x).Interior.ColorIndex = 22
            End If
        Next y
    Next x
End Sub

Before I defined y, I used a single row, like 11. It is like this: cells(11,x).value; the code ran without problems.

However, when I change from numbers to variable y, I get an error: Error 13, type mismatch.

What is the source of this error?

2
  • You should format your code as such. There is an orange ? that you can click when editing to see how. Commented Aug 24, 2015 at 19:46
  • Why wouldn't you just use Conditional Formatting and not worry about coding? Commented Aug 24, 2015 at 19:56

1 Answer 1

1

put one more condition layer. Actually if you have a cell with a in it and you multiply it by 5 , you usually get a type mismatch error.

If IsNumeric(Cells(y, x)) Then
    If Cells(y, x).Value < 0.9 * Cells(y, x - 3).Value Or Cells(y, x).Value > 1.1 * Cells(y, x - 3) Then

        Cells(y, x).Interior.ColorIndex = 22

    End If
End If
Sign up to request clarification or add additional context in comments.

1 Comment

I found my data contains "#Div/0!", that caused the issue. I did the code you suggested, it works! Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.