在VBA中向变量列表/数组添加元素

时间:2017-03-06 09:43:30

标签: excel-vba vba excel

我想添加一个项目列表。

vList as variant
vList = RefData.NameList
iCount = UBound(vList)
If RefData.Mode = "On" Then
  vList.Add("-2")

RefData是一张带参考数据的工作表。我的名字列表返回值3和9.如果模式为“on”,我希望它返回3,9和-2。

抛出物体错误。请帮助。

1 个答案:

答案 0 :(得分:1)

数组不是对象,因此没有可以调用的任何属性或方法。您需要调整数组大小,然后添加像这样的项目

Dim counter as long
vList as variant
vList = RefData.NameList
iCount = UBound(vList)
If RefData.Mode = "On" Then
  vlist = Application.transpose(vlist)
  counter = ubound(vList)
  redim preserve vlist(1 to counter +1)
  vlist(counter + 1) = -2
  vlist = Application.transpose(vlist)
End If

转置是必要的,因为为Variant分配范围始终会创建一个2D数组,如果使用Preserve来维护其内容,则只能调整数组的最后一个元素。