在excel中为特定数量的输入字段创建数组

时间:2014-05-12 12:27:51

标签: excel excel-vba vba

我想在excel中创建一个输入框以输入一定数量的记录。我设法让代码工作正常,但我希望for循环运行一段特定的时间(变量n)。

Sub fillInArray()

// Dim n As Integer
// n = InputBox("Provide number")

Dim StudentName(1 To 5) As String

   For i = 1 To 5

    StudentName(i) = InputBox("Enter student Name")
    Cells(i, 1) = StudentName(i)
   Next

End Sub

只有当我像这样调整我的代码时,它才能正常工作。

Sub fillInArray()

Dim n As Integer
n = InputBox("Provide number")

Dim StudentName(1 To n) As String

   For i = 1 To n

    StudentName(i) = InputBox("Enter student Name")
    Cells(i, 1) = StudentName(i)
   Next

End Sub

有人对我做错了什么的想法?

1 个答案:

答案 0 :(得分:0)

考虑:

Sub fillInArray()
    Dim n As Long, i As Long
    n = InputBox("Provide number")
    ReDim StudentName(1 To n) As String
       For i = 1 To n
            StudentName(i) = InputBox("Enter student Name")
            Cells(i, 1) = StudentName(i)
       Next
End Sub