To create a VBA code macro that applies cell formatting based on values in columns, you can use the following steps:
- Open the Excel workbook where you want to create the macro.
- Press
Alt + F11to open the Visual Basic Editor. - In the VBA Editor, go to
Insert > Moduleto create a new module. - Paste the following code into the module:
Sub ApplyCellFormatting()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to the name of your sheet
Dim rng As Range
Dim iRow As Long
Dim iCol As Long
' Set the range to apply formatting
Set rng = ws.Range("A2:B10") ' Change the range to match your data
' Loop through each row in the range
For iRow = 1 To rng.Rows.Count
' Loop through each column in the row
For iCol = 1 To rng.Columns.Count
' Determine the formatting based on the column value
Select Case rng.Cells(iRow, iCol).Value
Case 1
rng.Cells(iRow, iCol).Interior.Color = vbYellow
Case 2
rng.Cells(iRow, iCol).Interior.Color = vbGreen
Case Else
rng.Cells(iRow, iCol).Interior.Color = vbWhite
End Select
Next iCol
Next iRow
End Sub
- Modify the code to fit your specific requirements, such as changing the sheet name, range, and formatting conditions.
- Save the module and close the VBA Editor.
- To run the macro, press
Alt + F8, select the macro, and clickRun.
This VBA code macro will loop through each cell in the specified range and apply formatting based on the value in each cell. You can customize the formatting conditions and range to suit your needs.