arrays - excel VBA用数组值填充listobject取决于数组变量/字符串的数据类型
问题描述
我必须在 Excel 的 Listobjects 中操作数据,而不是用循环填充列,我试图将数组的值一次性粘贴到 listobject 位置以加快速度(访问列表对象和单元格一一更新非常减缓)。
几周前我在 SO: Pass ListObject to array 中发布了这个问题。类型变量字符串错误
不过,我正在观察以下内容:
'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。
解决方案
当数组是一维数组时,它应该是水平的。这就是为什么我只在所有单元格中粘贴了第一个值。
为了在列中正确粘贴一维数组,需要将其转置为
mylistObject.ListColumns(4).DataBodyRange.item(5).Resize(UBound(otherArray) + 1, 1).value =application.transpose(other_array)
其中 other_array 是一个维度,我们希望使用它从第 5 项垂直填充第 4 列。
推荐阅读
- assembly - AMD64 程序集:从函数正确返回浮点数
- c# - 自定义窗口类和装饰层
- javascript - 使用三元运算符递归附加到数组不起作用
- excel - Excel Solver Evolutionary 的背后是什么?
- php - 在 Laravel 的模型事件中获取 $request 对象(例如创建、更新等)
- android - 如何使用 Android 自动填充 API
- javascript - 偶数访问时显示缓存的网页,奇数访问时在前端获取
- nhibernate - 如何在控制台应用程序中调用它的同一线程上继续异步方法调用(SynchronizationContext?)
- python - 修复试图在 for 循环中的切片副本上设置值
- css - 我的网站引导列 (col-md-4) 在某些地方溢出,我似乎无法隔离问题