首页 > 解决方案 > 如何输入数组中行数的值?

问题描述

我想输入将在行中使用的帕斯卡三角形中的Dim i(10, 10) As Integer行数。

下面是没有这个功能的代码:

Sub PascalTriangle()

    Dim i(10, 10) As Integer
    Dim p, j As Integer

    i(0, 0) = 1
    i(1, 0) = 1
    i(1, 1) = 1

    For p = 2 To 10 'put one for the first column, here the number of row is 10
        i(p, 0) = 1

        For j = 1 To p
            i(p, j) = i(p - 1, j - 1) + i(p - 1, j)
        Next
    Next

    For p = 0 To 10
        For j = 0 To p
            Cells(p + 1, j + 1) = i(p, j)
        Next
    Next
End Sub

标签: excelvbauser-input

解决方案


请试试这个:

Sub PascalTriangle_ChooseNoOfRows()
    Dim i() As Long, p As Long, j As Long, lngR As Long, inpAns As String

    inpAns = InputBox("Now much rows must Pascal function process?", "Choose the number of rows", 10)
    If inpAns = "" Then Exit Sub
    If IsNumeric(inpAns) Then
        lngR = CLng(inpAns)
    Else
        MsgBox "You must write a number!": Exit Sub
    End If
    ActiveSheet.Cells.Clear
    ReDim i(lngR, lngR)
    i(0, 0) = 1: i(1, 0) = 1: i(1, 1) = 1

    For p = 2 To lngR
        i(p, 0) = 1
        For j = 1 To p
            i(p, j) = i(p - 1, j - 1) + i(p - 1, j)
        Next j
    Next
    For p = 0 To lngR
        For j = 0 To p
            Cells(p + 1, j + 1) = i(p, j)
        Next j
    Next
End Sub

推荐阅读