【发布时间】:2019-12-10 00:38:03
【问题描述】:
我必须在 Excel 的 Listobjects 中操作数据,而不是使用循环填充列,我试图一次性将数组的值粘贴到 listobject 位置以加快速度(访问列表对象和单元格更新一个一个非常慢)。
几周前我在 SO 中发布了这个问题: Pass ListObject to array. type variable String error
不过,我观察到以下几点:
'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。
【问题讨论】:
-
这与它是一个字符串无关。如果您逐步浏览,您会看到
otherarray是一维的,因此需要转置(默认情况下,它是“水平”或写入工作表时为一行)。 -
天啊!!!!!!然后用 application.transpose(otherarray) 转置它。我会将您的答案标记为“答案”,但我只能投票,没有可能标记为答案。谢谢朋友。
标签: arrays excel vba populate listobject