In this article I will explain how you can use VBA to change the italic fontproperty of cells and ranges. I have also provided an example on how to check if a cells has the italic fontproperty on or off.
You can download the code and file related to this article here.
The following line of code makes the font in cell A1 italic:
Range("A1").Font.Italic = True
Range("A1").Font.FontStyle = "Italic"
The following line of code removes the italic fontproperty:
Range("A1").Font.Italic = False
Range("A1").Font.FontStyle = "Regular"
Example 1, Set Italic Property:
In this example there are a set of drop down lists in row 1. Each drop down list has the values “Yes” and “No”. For more information about creating drop down lists in Excel please see Excel VBA Drop Down Lists. If the user selects “Yes” the text in the cell under the drop down list will become italic. If the user selects “No” the italic fontstyle from the cell below the drop down list will be removed. The “Yes”, “No” values for the drop down lists are in sheet 2:
The user can select “Yes” and “No” from the drop down lists:
The cell under the drop down list turns italic:
More italic font:
The program uses a worksheet_change event handler. The event handler executes when the user selects a value from the drop down lists:
'Executes when the user selects a new values from the drop down lists Private Sub worksheet_change(ByVal target As Range) Dim i As Integer For i = 1 To 6 'checks if the Yes property has been selected If Cells(1, i) = "Yes" Then 'changes the font to italic Range(Cells(2, i), Cells(2, i)).Font.Italic = True Else 'removes the italic font property Range(Cells(2, i), Cells(2, i)).Font.Italic = False End If Next i End Sub
In this example when the user presses the Run button the program will loop through the cells in row 2. If the cell in row 2 has the italic fontstyle the cell above in row 1 will be colored green :
In the figure below the italic fontstyle was removed from cell C2 and the fontstyle in cell B2 was changed to italic. After pressing the run button:
The code below executes when the user presses the run button:
'executes when the user presses the run button Private Sub btnRun_Click() Dim i As Integer 'loops through row 2 For i = 1 To 6 'checks if the font in the cell is bold If Range(Cells(2, i), Cells(2, i)).Font.Italic = TrueThen 'changes the color of the cell in row 1 to green Range(Cells(1, i), Cells(1, i)).Interior.Color = 3394611 Else 'removes any previous color applied to the content of the 'cell in row 1 Range(Cells(1, i), Cells(1, i)).Interior.Color = xlNone End If Next i End Sub
The If statement below checks if the font in the cell is italic:
If Range(Cells(2, i), Cells(2, i)).Font.Italic = TrueThen ... End If