|
楼主 |
发表于 2014-9-10 21:33
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
本帖最后由 liu-aguang 于 2014-9-11 08:57 编辑
八、转置数组出错
症状:
数组元素字长超过一定值导致转置出错
- Sub test()
- Dim x, y
- ReDim x(1 To 2, 1 To 2)
- x(1, 1) = String(1000, "a")
- x(1, 2) = String(100, "b")
- x(2, 1) = String(50, "c")
- x(2, 2) = String(10, "d")
- y = Application.Transpose(x) '错误发生在这里
- End Sub
-
复制代码 原因:
转置,数组元素字符串长度不能超过255个。
办法1:
构建一个自定义的转置函数。
- Sub Transpose1_Solve()
- Dim arr() As Variant
- Range("A1:B1") = Array("A", String(256, "B"))
- arr = Range("A1:B1")
- Range("A3:A4") = TransposeDim(arr)
- End Sub
- Function TransposeDim(vArrTrans As Variant) As Variant
- Dim X As Long, Y As Long
- Dim XUpper As Long, YUpper As Long
- Dim XLower As Long, YLower As Long
- Dim tempArray As Variant
- XUpper = UBound(vArrTrans, 2)
- XLower = LBound(vArrTrans, 2)
- YUpper = UBound(vArrTrans, 1)
- YLower = LBound(vArrTrans, 1)
- ReDim tempArray(XLower To XUpper, YLower To YUpper)
- For X = XLower To XUpper
- For Y = YLower To YUpper
- tempArray(X, Y) = vArrTrans(Y, X)
- Next Y
- Next X
- TransposeDim = tempArray
- End Function
复制代码 办法2:
在2010以上版本中,如果数组类型是字符串类型数组,则不受限制。
- Sub test()
- Dim x, y
- ReDim x(1 To 2, 1 To 2) As String
- x(1, 1) = String(1000, "a")
- x(1, 2) = String(100, "b")
- x(2, 1) = String(50, "c")
- x(2, 2) = String(10, "d")
- y = Application.Transpose(x)
- End Sub
复制代码
|
|