如何在excel vba中创build一个没有设置限制的数组?

我想用一个数组创build一个数字列表,但是我不想知道最后一个数字,而是依赖于其他因素,例如你问用户什么是最高限制,数组将停在那里。

我创build了一个数组,它会产生一个数字列表,但是当最后的数字是已知的例如:

Sub makearray50() 'creates a list of numbers from 1 to 50 Dim i As Integer Dim theArray(1 To 50) As Double For i = 1 To 50 theArray(i) = Int(0 + i) Next i For i = 1 To 50 Sheets("ARRAY").Cells(i, 1).Value = theArray(i) Next i End Sub 

所以我想我会尝试一个未知的上限,这是我的尝试:

 Sub makearrayx() 'creates a list of numbers from 1 to x Dim i As Integer Dim x As Integer x = 10 Dim theArray(1 To x) As Double For i = 1 To x theArray(i) = Int(0 + i) Next i For i = 1 To x Sheets("ARRAY").Cells(i, 1).Value = theArray(i) Next i End Sub 

我想通过尝试x“已知”,然后我可以编辑它,并问用户他们想要什么(使用input框)​​,但VBA不会允许它,我得到错误消息:

错误消息截图

你可以创build一个函数来返回这样的数组:

 Function MakeArray(n As Long) As Variant 'Creates a 1-based array containing the values '1,2,...,n Dim A As Variant, i As Long ReDim A(1 To n) For i = 1 To n A(i) = i Next i MakeArray = A End Function 

请注意我如何使用Long而不是Integer 。 在电子表格中有超过一百万行,使用Integer迟早会要求溢出错误。 还要注意,不需要将A声明为数组。 变体可以保存数组, ReDim语句使其成为一个数组。

你可以像这样testing它:

 Sub test() Dim theArray As Variant, n As Long, i As Long n = InputBox("How many elements") theArray = MakeArray(n) For i = 1 To n Cells(i, 1).Value = theArray(i) Next i End Sub 

最后,如果你有一个情况,你的数组一直在dynamic增长,重构代码可能更有意义,所以它使用一个集合,这是最接近的VBA来有一个内置的dynamic列表数据结构。

以下是如何重新定义数组的一个简单示例:

 Sub test() Dim i& Dim theArray() Dim cel As Range i = 0 For Each cel In Range("A1:A28") ReDim Preserve theArray(i) 'This will resize the array, but keep previous values theArray(i) = cel.Value i = i + 1 Next cel For i = LBound(theArray) To UBound(theArray) 'this will just show you the array is working in the Immediate Window Debug.Print theArray(i) Next i End Sub 

在我的例子中,我把行号放在A1:A28中。 它每次正确地增加数组的大小。 你可以像这样疯狂,比如添加If语句,( If cel.value = "Gotham" Then theArray(i) = cel.value )或者其他有助于确定数组大小的方法。

或者,如果你想保留你的例子,并设置arrays大小,你可以。 说我有我的列A,但数据大小(行数)总是改变。 您可以将数组大小设置为(例如) Application.WorksheetFunction.Counta(Range("A:A"))以获取可用于调整数组大小的非空白单元格的数量。

这是最简单的方法。 这个小组将会:

– >询问用户数组的上限
– >创build一个数组
– >打印到工作表的值

 Sub makearrayx() Dim i, x As Integer Dim theArray As Variant x = InputBox("Tell me array limit") ReDim theArray(1 To x) For i = 1 To x theArray(i) = i Next For i = 1 To x Sheets("ARRAY").Cells(i, 1).Value = theArray(i) Next End Sub