WITH is another useful statement in Excel VBA. It usually used to ignore using the same object name for changing various aspects. For example if you would like to change the (1) font color (2) font size (3) font italic etc. then you simply write the codes like below:
But this would be more easier if you use WITH statement like below, where Cells(4,5).Font used only once. You then type the property you need after a dot:
With Statements are quite intuitive, so we don't really need to say too much about them. But just remember: if you're typing the same object over and over, you might do better to use a With ... End With statement. Writing with WITH statement the VBA code will run faster due to it will not read the same object again and again.
Example:
With an example it would be very clear to you. Assume that, B2 cell contains "Hello Bangladesh" like below:
Cells(4,5).Font.Color = RGB(254,00,00) Cells(4,5).Font.Size = 12 Cells(4,5).Font.Italic = True
But this would be more easier if you use WITH statement like below, where Cells(4,5).Font used only once. You then type the property you need after a dot:
With Cells(4,5).Font .Color = RGB(254,00,00) .Size = 12 .Italic = True End With
With Statements are quite intuitive, so we don't really need to say too much about them. But just remember: if you're typing the same object over and over, you might do better to use a With ... End With statement. Writing with WITH statement the VBA code will run faster due to it will not read the same object again and again.
Example:
With an example it would be very clear to you. Assume that, B2 cell contains "Hello Bangladesh" like below:
Image 1: Simple text
Now use the below code in module and run it. It will bring the result like below:
Sub fontcolor1() With Cells(2, 2).Font .Italic = True .Size = 14 .Color = vbBlue End With End Sub
Image 2: Format changed
|||| Please SUBSCRIBE our YouTube Channel ||||
https://www.youtube.com/channel/UCIWaA5KCwZzBGwtmGIOFjQw
|||| Please SUBSCRIBE our YouTube Channel ||||
https://www.youtube.com/channel/UCIWaA5KCwZzBGwtmGIOFjQw