我需要将两个数组粘贴到电子表格中。由于每个目标都是一列,我正在使用Transpose命令,如下所示:
Selection = WorksheetFunction.Transpose(arr1)
这适用于其中一个阵列,但另一个给我一个无效的过程调用(错误5)。两个数组都是相同的大小:arr(1到79)。
我能说的两者之间的唯一区别是“good”数组中的所有值都是Variant / String,而“bad”数组中的大多数值都是Variant / Date。
这真的会有所作为吗?如果是这样,有没有办法转换后一个数组中的值?
答案 0 :(得分:0)
正确编码以下内容应该有效:
Sub DepositArrays()
Dim ary1(1 To 2) As String, ary2(1 To 2) As Date
ary1(1) = "James"
ary1(2) = "Ravenswood"
ary2(1) = DateSerial(1945, 1, 20)
ary2(2) = Date
With Application.WorksheetFunction
Range("A1:A2") = .Transpose(ary1)
Range("B1:B2") = .Transpose(ary2)
End With
End Sub
收率:
如果没有TRANSPOSE()
,代码会运行,但不会产生正确的结果。
答案 1 :(得分:0)
为什么不使用range
:
Private Sub Test()
Dim arr(79) As Variant
For i = o To UBound(arr)
arr(i) = Now
Next
Dim rng As Range
Set rng = Range(Cells(2, 2), Cells(81, 2))
rng = WorksheetFunction.Transpose(arr)
End Sub
另一个选项是一个简单的循环来迭代数组并将数据填充到工作表中:
Private Sub Test2()
Dim arr(79) As Variant
For i = o To UBound(arr)
arr(i) = Now
Next
For i = o To UBound(arr)
Cells(i + 1, 1) = arr(i)
Next
End Sub
答案 2 :(得分:0)
无论我使用Transpose
作为Application
类还是WorksheetFunction
类的成员,这两种方法都适合我。如果数组中的任何元素包含长度为> = 255个字符的字符串,则会出现类型不匹配错误,但我无法复制无效的过程调用错误。
您可以在空白工作簿中测试吗?
Sub foo()
Dim arr1(79), vals, rng As Range
Dim i As Long
For i = LBound(arr1) To UBound(arr1)
arr1(i) = DateAdd("d", i, #1/1/2016#)
Next
Set rng = Range("A1:A80")
rng = Application.Transpose(arr1)
vals = arr1
Set rng = rng.Offset(, 1)
rng = Application.WorksheetFunction.Transpose(arr1)
'Both methods work even if the destination range is the wrong size:
Set rng = rng.Offset(, 1).Resize(100)
rng = Application.Transpose(arr1)
Set rng = rng.Offset(, 1).Resize(50)
rng = Application.WorksheetFunction.Transpose(arr1)
End Sub