1

我一直犯同样的错误,我不知道它是什么。每次我做一个处理数组的 For-Loop 时(通常,尝试读取一个数组并将值写入第二个数组),它只从第一个数组中获取最后一个值并将其写入第二个数组的每个插槽中大批。

这是我正在研究的最简单/最短的副本。它应该从 A1:A10 中读取值并将它们写入 B1:K1。

Sub Problem1()
    Dim a(1 To 10) As Single
    Dim b(1, 10) As Single
    Dim i As Integer



    For i = 1 To 10
        a(i) = Range("A" + CStr(i)).Value
    Next i

    For i = 1 To 10
        b(1, i) = a(i)
    Next i

    Range("B1:K1") = b(1, 10)

End Sub
4

5 回答 5

4
Range("B1:K1") = b(1, 10)

这只会复制一个数组元素。

您可以执行以下操作:

Range("B1:K1").Value = Application.WorksheetFunction _
    .Transpose(Range("A1:A10"))

不幸的是,要将原始值存储在数组中(使用我的方法)需要将其声明为 Variant:

Sub Problem1()
    Dim a As Variant

    a = Range("A1:A10")

    Range("B1:K1") = Application.WorksheetFunction.Transpose(a)
End Sub

如果您仍想同时使用这两个数组:

Sub Problem1()
    Dim a As Variant
    Dim b(1 To 10) As Single
    Dim i As Integer

    a = Range("A1:A10")
    For i = 1 To 10
        b(i) = a(i, 1)
    Next i
    Range("B1:K1") = b
End Sub
于 2013-06-23T00:37:01.467 回答
1
Sub Problem1()
    Dim a(1 To 10) As Single
    Dim b(1, 10) As Single
    Dim i As Integer

    For i = 1 To 10
        a(i) = Range("A" + CStr(i)).Value
    Next i

    For i = 1 To 10
        b(1, i) = a(i)
    Next i

    Range("B1:K1") = b()
End Sub
于 2014-12-11T10:48:56.447 回答
0

尝试使步骤尽可能清晰,并在一个步骤中读取/写入所有值,以避免输出更改输入(重叠单元格)。流量应该是[Read]->[Calc]->[Write]

Sub Problem1()
    Dim a() as Variant, b() as Variant, i as Integer

    'Get Values
    a = Range("A1").Resize(10,1).Value2

    'Transform the arrays in any way you need.
    'Make sure the intent is clear
    ReDim b(1 to 1, 1 to 10)
    For i=1 to 10
        b(1,i) = a(i,1)
    Next i

    'Set Values
    Range("B1").Resize(1,10).Value2 = b

End Sub
于 2013-06-24T00:40:24.333 回答
0

对于你想要的,你可以做的更好的方法是:

Sub Problem1()

Dim a(1 To 10) As Single
Dim i As Integer

For i = 1 To 10
    a(i) = Range("A" + CStr(i)).Value
Next i

Range("B1:K1") = a
End Sub

至于您当前的实现有什么问题,是您为一组单元格的整个范围分配了一个。更好的是循环遍历数组的内容以将其单独输出到每个单元格中。但是如我上面的示例所示,vba 会本机处理此问题(将数组输出到一系列单元格)。

于 2013-06-23T00:35:29.457 回答
0
Sub Problem1()
Dim i, j As Integer
j = 2

For i = 1 To 10
    ActiveSheet.Cells(1, j).Value = ActiveSheet.Range("A" & i)
    j = j + 1
Next i
End Sub
于 2013-06-23T01:13:05.797 回答