VBA for Excel 2007 tutorial-print a Pascal triangle


VBA 2D arrays to print a Pascal triangle

In this example, We use VBA two-dimensional array to print a table that represents a Pascal triangle(size=10). In the Pascal triangle, every element is the sum of the element directly above it and the element to the left of the element directly above it. See the example Pascal triangle below:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1



The table will fill with a series of numbers starting from 1 to 25. In each row there are five numbers.

To the run the example program, you will need one Form and one CommandButton.



VBA for Excel: using VBA 2D array to a Pascal Triangle
VBA code for this example:


Option Explicit
 
Private Sub CommandButton1_Click()
   
    Dim pascalTr(10, 10) As Integer
    Dim row, col As Integer
    pascalTr(0, 0) = 1
    pascalTr(1, 0) = 1
    pascalTr(1, 1) = 1
    For row = 2 To 10
        pascalTr(row, 0) = 1
        For col = 1 To row

         pascalTr(row, col) = pascalTr(row - 1, col - 1) + pascalTr(row - 1, col)
        Next
    Next
    For row = 0 To 10
   
        For col = 0 To row
          Cells(row + 1, col + 1) = pascalTr(row, col)
          Next
    Next
End Sub

Comments

mmm comment

 mmm

Request you to please explain this code.


2018-01-11
mmm comment

 mmm

Request you to please explain this code.


2018-01-11
Vikas Kulhari comment

 Vikas Kulhari

Hi, Here is another best way to design a Pascal Triangle dynamically.

Sub pascal()
Dim book As Excel.Workbook
Dim sht As Worksheet
Set book = ThisWorkbook
Set sht = book.Worksheets("sheet1")
a = InputBox("Enter the Number", "Fill")
For i = 1 To a
For k = 1 To i
If i >= 2 And k >= 2 Then
sht.Cells(i, k).Value = sht.Cells(i - 1, k - 1) + sht.Cells(i - 1, k)
Else
sht.Cells(i, k).Value = 1
End If
Next k
Next i
End Sub


2017-01-20




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.