Please clearly write the VBA code that correctly answers the following question:
ID: 3758477 • Letter: P
Question
Please clearly write the VBA code that correctly answers the following question: #2
Create a VBA subroutine called Checkerboard that will take a selection of cells(not a fixed range) and then color every other cell red and every other black. Red should go in the upper left corner of the selection. You may want to employ the mod funvtion in VBA. If, for example, it is an odd row then you'll color the odd columns red. If it is an even row, you'll color the even columns red. Instead of recording a Macro, an easy way to do this is " Selection.Cells(i,j). Interior.Color=225"(For RED) and "Selection.Cells(i,j).Interior.Color=0"(For BLACK).
Explanation / Answer
Sub loops_exercise()
Const NB_CELLS As Integer = 10 '10x10 checkerboard of cells
Dim offset_row As Integer, offset_col As Integer ' => adding 2 variables
'Shift (rows) starting from the first cell = the row number of the active cell - 1
offset_row = ActiveCell.Row - 1
'Shift (columns) starting from the first cell = the column number of the active cell - 1
offset_col = ActiveCell.Column - 1
For r = 1 To NB_CELLS 'Row number
For c = 1 To NB_CELLS 'Column number
If (r + c) Mod 2 = 0 Then
'Cells(row number + number of rows to shift, column number + number of columns to shift)
Cells(r + offset_row, c + offset_col).Interior.Color = RGB(200, 0, 0) 'Red
Else
Cells(r + offset_row, c + offset_col).Interior.Color = RGB(0, 0, 0) 'Black
End If
Next
Next
End Sub