通过循环输入框填充的动态数组

时间:2015-11-09 22:56:15

标签: arrays excel vba excel-vba

我试图让用户根据托盘数量输入重量。 NumberPallets是通过代码中其他位置的输入框设置的。

NumberPallets是3.我希望它循环3次并询问每个托盘的重量并将其存储到PalletWeights(p)中,所以它看起来像这样:

PalletWeight(1) = 200
PalletWeight(2) = 100
PalletWeight(3) = 300

TotalPalletWeight = 600

现在它给了我一个下标错误,我相信它是因为我没有正确地做这个数组。我用谷歌搜索试图使用PalletWeight(Ubound(PalletWeight)),但这也不起作用。其他Google搜索几乎不会产生单独获取InputBox数据而不是以逗号分隔列表的结果。

我需要更改什么来实现此功能?

ReDim PalletWeights(1 to NumberPallets) 'Added based on an answer on this question

Dim PalletWeights() As String 'Array of pallet weights
Dim p As Integer
p = 1
Do While p <= NumberPallets

    PalletWeights(p) = Application.InputBox(Prompt:="What is the weight of pallet number " & p & "?", Type:=1)
    p = p + 1
Loop

TotalPalletWeight = Application.WorksheetFunction.Sum(PalletWeights)

新的完整工作代码:

'Pallet Weights
Dim PalletWeights() 'Array of pallet weights
Dim p As Integer
p = 1

ReDim PalletWeights(1 To NumberPallets)

Do While p <= NumberPallets

     'Total Weight
      PalletWeights(p) = Application.InputBox(Prompt:="What is the weight of pallet number " & p & "?", Type:=1)
      TotalWeight = TotalWeight + PalletWeights(p)
      p = p + 1

Loop

3 个答案:

答案 0 :(得分:1)

您已声明动态数组。在您明确调整大小之前,它不会调整大小。

尝试在Do循环之前添加

ReDim PalletWeights(1 to NumberPallets)

答案 1 :(得分:0)

只需要在循环后添加ReDim表达式。见下文。

Dim PalletWeights() As String 'Array of pallet weights
Dim p As Integer
p = 1
Do While p <= NumberPallets

 PalletWeights(p) = Application.InputBox(Prompt:="What is the weight of         pallet number " & p & "?", Type:=1)
 p = p + 1
Loop

ReDim PalletWeights(p)

TotalPalletWeight = Application.WorksheetFunction.Sum(PalletWeights)

答案 2 :(得分:0)

首先您需要使用ReDim分配数组大小,然后您可以将数据存储在数组中。在汇总数据时,这就是为什么需要将数组声明为整数而不是字符串。

    Public Sub ArraySum()
            Dim PalletWeights() As Integer 'Array of pallet weights
            Dim p, TotalPalletWeight As Integer
            ReDim PalletWeights(5)
            p = 1
            Do While p <= 5
            PalletWeights(p) = Application.InputBox(Prompt:="What is the weight of         pallet number " & p & "?", Type:=1)
             p = p + 1
            Loop
            TotalPalletWeight = Application.WorksheetFunction.Sum(PalletWeights)
            MsgBox TotalPalletWeight
    End Sub