adding values to variable array VBA

戏子无情 提交于 2019-12-31 08:31:33

问题


I am trying to loop through a table that has a column for "customers" and "dollar amount". If my loop finds a customer called "greg" or "henry" I want to add his "dollar amount" to an array of an unknown size.

Can someone please help me?


回答1:


If by unknown size, you mean that number of elements is unknown, you could use a dynamic array.

Dim aArray() As Single ' or whatever data type you wish to use
ReDim aArray(1 To 1) As Single
If strFirstName = "henry" Then
    aArray(UBound(aArray)) = 123.45
    ReDim Preserve aArray(1 To UBound(aArray) + 1) As Single
End If

Ubound(aArray) throws an error if the array hasn't been dimensioned, so we start by adding an element to it. That leaves us with an empty element at the end of the text, so your code should account for that. aArray(Ubound(aArray)-1) will give you the last valid element in the array.




回答2:


Private Sub ArrayMy(DataRange)
  Dim DataIndex() As String
  i = 0
  On Error Resume Next
  ReDim DataIndex(0)
  For Each c In DataRange
      DataIndex(i) = c
      i = i + 1
      ReDim Preserve DataIndex(i)
  Next
End Sub


来源:https://stackoverflow.com/questions/12663879/adding-values-to-variable-array-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!