![](/img/trans.png)
[英]How to convert string type array to variant type array - Excel VBA
[英]excel VBA populate listobject with array values depends on datatype of array variant/string
我必须在Excel的Listobjects中操作数据,而不是用循环填充列,而是尝试一次将数组的值粘贴到listobject的位置,以加快处理速度(访问列表对象和单元格一次更新非常慢)。
我几周前在SO中发布了这个问题:将ListObject传递给数组。 类型变量字符串错误
不过,我观察到以下情况:
'variables
Dim mylistObject As ListObject
Set mylistObject = ThisWorkbook.Sheets("training").ListObjects(1)
Dim i As Integer
' the two arrays to be pasted are defined differently
Dim theArray() As Variant
theArray = mylistObject.ListColumns(1).DataBodyRange.value
' where column 1 is populated with numbers.
Dim otherArray() As String
otherArray = Split("1,2,3,4,5,6,7,8,9", ",")
'lets paste both arrays with insertion point a particular cell (item 5)
' a) if the two ranges are the same size, i.e. one column copied I can do:
mylistObject.ListColumns(2).DataBodyRange.value = theArray
' b) lets paste the two arrays in from item 5 on using resize (note ubound of thearray is 9, i.e. base 1)
mylistObject.ListColumns(3).DataBodyRange.item(5).Resize(UBound(theArray), 1).value = theArray
' c) lets paste the otherarray in column 4 (note ubound of thearray is 8, i.e. base 0)
mylistObject.ListColumns(4).DataBodyRange.item(5).Resize(UBound(otherArray) + 1, 1).value = otherArray
'the classical but slow way to paste value by value is:
For i = LBound(otherArray) To UBound(otherArray)
mylistObject.ListColumns(5).DataBodyRange.item(4 + i).value = otherArray(i)
Next i
我得到了这个结果(见图),这确实很奇怪。 当数组为字符串类型时,为什么粘贴第二个数组(otherarray)不起作用。
如果您想知道为什么我不简单地将otherarray更改为variant,是因为那样我就无法使用split()方法生成otherarray。
当数组是一维数组时,它应该是水平的。 这就是为什么我只将firts值粘贴到所有单元格中的原因。
为了正确地将一维数组粘贴到列中,需要用
mylistObject.ListColumns(4).DataBodyRange.item(5).Resize(UBound(otherArray) + 1, 1).value =application.transpose(other_array)
其中other_array是一个demensionla,我们要使用它垂直填充项目5中的第4列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.