将二维数组转换为一维数组
如何使用Application.Index(array, row, column)
将范围(=multidimensional array)转换为单维数组时,如何在每个单元格的255个字符范围内工作?
以下截断的例子重现错误:
错误13.types不匹配
(完整的代码是在超级用户,我试图帮助另一个用户 )。
如何重现
-
打开一个新的Excel工作表并插入公式
=REPT("x",256)
到单元格A1
这会创build一个长度为256个字符的string,这个string对于最后一个步骤来说只有1个字符太长 -
打开VBA编辑器( Alt + F11 )并粘贴下面的代码
-
用F8逐行执行代码
Function StringLengthTest() Dim arr2D As Variant Dim arr1D As Variant arr2D = Rows(1) arr1D = Application.Index(arr2D, 1, 0) End Function
-
当Excel尝试将一个范围(2D)转换为一维数组而其中一个单元格超过255个字符时,您将在最后一行看到相同的错误。
为了certificate这一点,将=REPT("x",256)
更改为=REPT("x",255)
并再次运行代码。 这一次它会工作。
问题:我应该用另一种方式声明我的variables吗? 有没有更好的方法来将范围(始终是一个二维对象)转换为单维数组?
我知道我可以使用循环遍历数组,并将所有的二维数组值逐个保存到一维数组中。 但是这不是有效的。 想象一下真正的大床单。
到目前为止,从单元格到内存(一个数组)的最好方法是使用一个数组variables。 我认为你遇到的问题是索引而不是你的方法。
希望这个代码应该解释它。
Dim v_data As Variant Dim rw As Long, cl As Long ' for row and column Dim arr1d() As Variant Dim count As Long ' I'm going to use UsedRange to get the whole sheet .UsedSheet ' If you just want things from one row or column then just spec ' activesheet.range("A1:A100") or use cells() With ActiveSheet.UsedRange ReDim v_data(1 To .Rows.count, 1 To .Columns.count) v_data = .Value End With 'now we have all the things from that sheet. 'so to convert to 1d array where the cell value is say = 1 For rw = LBound(v_data) To UBound(v_data) For cl = LBound(v_data, 2) To UBound(v_data, 2) ' note the comma 2 for the second dimension bounds. If v_data(rw, cl) = 1 Then count = count + 1 ReDim Preserve arr1d(1 To count) arr1d(count) = v_data(rw, cl) End If Next cl Next rw For count = LBound(arr1d) To UBound(arr1d) Debug.Print arr1d(count) Next count
现在的诀窍就是把这个function放到一个需要几个参数(一个2d范围,你正在寻找的范围)的函数中,然后返回你的列表。
将数据重新存入工作簿
ActiveSheet.Cells(1, 1).Resize(UBound(arr1d), 1).Value = arr1d
根据数组的边界创build一个完全相同大小的范围,然后确保使用.value
只是popupvariables数组。