Table of Contents

Create a Pattern

Below we will look at a program in Excel VBA that creates a pattern.

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.

Crate a Pattern Result so Far

For example for i = 1 and j = 1 Excel VBA colors Cells(11) for i = 1 and j = 3 (Step 2) Excel VBA colors Cells(13) for i = 1 and j = 5 Excel VBA colors Cells(15) for i = 3 (Step 2) and j = 1 Excel VBA colors Cells(31) 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

Leave A Comment

Excel meets AI – Boost your productivity like never before!

At Formulas HQ, we’ve harnessed the brilliance of AI to turbocharge your Spreadsheet mastery. Say goodbye to the days of grappling with complex formulas, VBA code, and scripts. We’re here to make your work smarter, not harder.

Related Articles

The Latest on Formulas HQ Blog