如何更改数组vba中的现有数据

在Excel中,我有一个与他们的重量项目列表。 我在VBA中做了一个函数,只要总重量小于10,就可以从列表中选出一个随机项目。
在这个函数之前,我做了一个只包含零的数组,它应该属于一个项目。 当随机函数选取一个项目时,数组中的这个位置应该变成一个,但是这个函数的这个部分不起作用。
任何人都可以帮我解决这个问题/修复function?
这是我的代码:

Sub Test() Dim weight As Single, totWeight As Single Dim finish As Boolean Dim r As Integer Const maxWeight = 10 'Here it makes an array of only zero's Dim Arr(1 To 66) As String, i As Integer For r = 1 To 66 Arr(r) = 0 Next r Do Until finish = True 'Pick random row out of my Excel sheet r = Int((65 * Rnd()) + 2) 'The first are the titles (item, weight), so that's why I start from row 2 If (totWeight + Cells(r, 2)) < maxWeight Then 'Sum the picked weight up to the total weight totWeight = totWeight + Cells(r, 2) 'Change the position of the item in the array into a 1 'But it doesn't work --> Arr(r) = 1 Else 'Do as long as the weight is under 10 finish = True End If Loop 'It only prints zero's PrintArray Arr, ActiveWorkbook.Worksheets("Sheet1").[F1] End Sub (btw, this is the print function: Sub PrintArray(Data As Variant, Cl As Range) Cl.Resize(UBound(Data, 1)) = Data End Sub) 

我打了你的代码,这似乎是你的打印function的问题。 试试这个

 Sub PrintArray(Data As Variant, Cl As Range) Dim i As Integer For i = LBound(Data) To UBound(Data) Cl.Cells(i, 1).Value = Data(i) Next i End Sub 

如果你有兴趣为什么你的解决scheme没有工作,我认为它是因为你试图将数组赋值。 所以总是需要复制数组时,逐项执行…

看起来像你没有把数组放入数组的原因是因为该数组的方向倒退到您将数组元素的值转储回工作表的方式。 基本上,你用第一个元素(例如arr(1))填充所有66个单元格。 如果你这样做了足够多的时间,那么随机的r var迟早会变成1,并且数组的第一个元素将会得到1 。 在这种情况下,所有的单元格都是一个单元格。

使用单维数组,您可以使用Excel应用程序对象的TRANSPOSE函数将您的数组从基本上1行×66列转换为66行×1列。

 Sub PrintArray(Data As Variant, Cl As Range) Cl.Resize(UBound(Data)) = Application.Transpose(Data) End Sub 

这是一个bandaid修复和Application.Transpose有一些限制(某处无符号int – 1)。

如果您正在创build一个数组,以便在工作表上填充一个单元格范围,请从2维数组开始,并坚持使用它。 保持数组的排名正确,并且不会有任何问题将数据转储回工作表。

 Sub Test() Dim weight As Single, totWeight As Single Dim r As Long Const maxWeight = 10 'Here it makes an array of only zero's Dim Arr(1 To 66, 1 To 1) As String, i As Integer For r = LBound(Arr, 1) To UBound(Arr, 1) Arr(r, 1) = 0 Next r With ActiveWorkbook.Worksheets("Sheet1") Do While True 'Pick random row out of my Excel sheet r = Int((65 * Rnd()) + 2) 'The first are the titles (item, weight), so that's why I start from row 2 If (totWeight + .Cells(r, 2)) < maxWeight Then 'Sum the picked weight up to the total weight totWeight = totWeight + .Cells(r, 2) 'Change the position of the item in the array into a 1 Arr(r, 1) = 1 '<~~ Else 'just exit - no need to set a boolean Exit Do End If Loop PrintArray Arr, .Range("F2") End With End Sub Sub PrintArray(Data As Variant, Cl As Range) Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data End Sub 

这对于66行来说并没有太大的区别,但是对于LubošSuk和他的出色答案,通过100K单元循环将数组值返回工作表的过程相当缓慢,而且我们在相当大的数据块上使用了数组,因为它们速度更快 将数值全部撤回是几乎是瞬间的。