Create a Pattern in Excel VBA

 

You can create a pattern of colors on your worksheet by using a double loop, the Step keyword and the Offset property in Excel VBA.

Situation:

Create a Pattern in Excel VBA

Place a command button on your worksheet and add the following code lines:

1. First, we declare two variables of type Integer. One named i and one named j.

Dim i As Integer, j As Integer

2. Second, we add two For Next loops.

For i = 1 To 5 Step 2
    For j = 1 To 5 Step 2

3. Next, we add the line which changes the background color of the cells to light gray.

Cells(i, j).Interior.ColorIndex = 15

Note: instead of ColorIndex number 15 (light gray), you can use any ColorIndex number.

4. Close the two For Next loops.

    Next j
Next i

5. Test the program.

Result so far.

Create a Pattern Result so Far

For example, for i = 1 and j = 1, Excel VBA colors Cells(1,1), for i = 1 and j = 3 (Step 2), Excel VBA colors Cells(1,3), for i = 1 and j = 5, Excel VBA colors Cells(1,5), for i = 3 (Step 2) and j = 1, Excel VBA colors Cells(3,1), etc.

6. We are almost there. The only thing we need to do, is color the cells which are offset by 1 row below and 1 column to the right of the cells already colored. Add the following code line to the loop.

Cells(i, j).Offset(1, 1).Interior.ColorIndex = 15

7. Test the program.

Result:

Create a Pattern Result

If you're new here, welcome to Excel Easy! Join over 1 million monthly Excel learners. You can find popular courses here: Data Analysis in Excel and Excel VBA.