通过循环input框填充的dynamic数组

我试图让用户input基于托盘数量的重量。 NumberPallets通过代码中其他位置的input框设置。

NumberPallets是3.我想这个循环3次,并要求每个托盘的重量和存储到PalletWeights(p),所以它看起来像这样:

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

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

我需要改变什么来使这个function?

 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 

你已经声明了一个dynamic数组。 直到你明确地确定它的大小,它的大小是不一样

尝试在Do循环之前添加

 ReDim PalletWeights(1 to NumberPallets) 

只需要在循环之后添加ReDimexpression式。 见下文。

 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) 

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

  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