問題描述
通過 VBA 中的輸入創建數組 (Creath an array by input in VBA)
我想創建一個數組來存儲公司不同部門的名稱。首先,我讓用戶輸入部門的總數,然後創建一個數組,讓用戶輸入部門的名稱。但是編譯器說數組的索引超出範圍。
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
</code></pre>
參考解法
方法 1:
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
(by Chih‑Yu Chang、Dang D. Khanh)
參考文件