Saturday 5 August 2017

Asterisk Triangle in Excel VBA Through Loops

In below code you can see how to create different Triangles of asterisk in Excel VBA through Loops.


You can change the value in Cells if you want different than asterisk.

This is one of the most asked interview questions about excel vba.


Code used to create above

Sub loop_test1()
    For i = 1 To 20
        For j = 1 To 21 - i
        Cells(i, j).Value = "*"
        Cells(i, j).Interior.Color = vbYellow
        Next
    Next
    Range("A1").CurrentRegion.Select
    Selection.Columns.AutoFit
End Sub



Code for Loop Test 2 used to create above triangle

Sub loop_test2()
    For i = 20 To 1 Step -1
        For j = 1 To i
        Cells(i, j).Value = "*"
        Cells(i, j).Interior.Color = vbYellow
        Next
    Next
    Range("A1").CurrentRegion.Select
    Selection.Columns.AutoFit
End Sub


Code for Loop test 3 (smallest triangle)

Sub loop_test3()
    For i = 1 To 3
        For j = 4 - i To i + 2
        Cells(i, j).Value = "*"
      Cells(i, j).Interior.Color = vbYellow
        Next
    Next
    Range("A1").CurrentRegion.Select
    Selection.Columns.AutoFit
End Sub
Code created the above Pyramid is here

Sub loop_test4()
    For i = 1 To 10
        For j = 10 - i + 1 To i + 9
        Cells(i, j).Value = "*"
      Cells(i, j).Interior.Color = vbYellow
        Next
    Next
    Range("J1").CurrentRegion.Select
    Selection.Columns.AutoFit
End Sub


1 comment:

  1. Hi Sid, I have question, not sure how can I contact you aside from here

    ReplyDelete