Chih-Yu Chang
Chih-Yu Chang

Reputation: 1

Creath an array by input in VBA

I would like to create an array to store the name of different departments of the company. First of all, I make users to input the total amount of departments and then create a array, allowing users to key in the name of departements. But the compiler said the index of array is out of range.

Dim myarray As Variant
myarray = Array

deptnum = InputBox("Please enter the total amount of departments.")

For k = 0 To deptnum
x = InputBox("Please enter the name of department:"
x = myarray(k)
Next

Upvotes: 0

Views: 54

Answers (1)

Dang D. Khanh
Dang D. Khanh

Reputation: 1471

If you still use the array, you can use the redim array, then use array(index) to assign the name you have entered.

Sub Test()
    Dim departments() As String
    Dim x As String

    deptnum = InputBox("Please enter the total amount of departments.")
    If Not (IsNumeric(deptnum)) Then Exit Sub
    ReDim departments(deptnum - 1)

    For k = 0 To deptnum - 1
        x = InputBox("Please enter the name of department:")
        departments(k) = x
    Next
End Sub

Upvotes: 1

Related Questions