Saturday, 5 August 2017

Sum all digits of a number

Here below find the code to sum all the digits of a number

Subprocedure will ask an input and return a message box of sum.

Sub sum_digits()
num = InputBox("Enter digits to sum")
    Do While Number >= 1
       ss = ss + num Mod 10
        num = Int(num / 10)
    Loop
    MsgBox ss
End Sub



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