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

Zie*_*ezo 3 arrays excel vba excel-vba

在Excel中,我有一个重量项目列表.我在VBA中创建了一个函数,只要总重量低于10,就可以从列表中选择随机项.
在此函数之前,我创建了一个只有零的数组,它应该属于一个项目.当随机函数选择一个项目时,数组中的这个位置应该变成一个,但是这部分函数不起作用.
任何人都可以帮我解决这个问题/修复功能吗?
这是我的代码:

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) 
Run Code Online (Sandbox Code Playgroud)

Lub*_*Suk 5

我对您的代码进行了调试,似乎问题在于您的打印功能.试试这个吧

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
Run Code Online (Sandbox Code Playgroud)

如果你有兴趣为什么你的解决方案不起作用,我认为它是因为你试图将数组赋值.所以总是在需要复制数组时,逐项完成...