数组未从For Loop VBA填充

时间:2014-03-31 10:03:57

标签: arrays excel vba

我正在尝试创建一个填充for循环的单元格条目数组(例如A6,B6等)。

然而阵列

    MyArray

总是空的,我无法弄清楚为什么它没有被填充在for循环中。下面是(代码的相应部分正在做其他事情)我的代码:

    Sub ListSheets()

    ' Defining all variables (objects) used within the code, establishing their
    'classes                                   

   Dim i As Integer
   Dim array_size As Integer
   Dim MyArray() As String

   array_size = 26
   ReDim MyArray(array_size) As String

   For intLoop = 1 To 26
   MyArray(intLoop, 1) = Chr$(64 + intLoop) + "6"
   Next

   Set CopyFrom = MyArray
   Sheets("vba_deposit").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value

   End Sub

有什么想法吗?

非常感谢提前。

2 个答案:

答案 0 :(得分:2)

试试这个:

Sub ListSheets()
   Dim i As Integer
   Dim array_size As Integer
   Dim MyArray() As String

   array_size = 26
   ReDim MyArray(1 To array_size, 1 To 1)

   For intLoop = 1 To 26
        MyArray(intLoop, 1) = Chr$(64 + intLoop) + "6"
   Next

   Sheets("vba_deposit").Range("A1").Resize(UBound(MyArray)).Value = MyArray    
End Sub

您使用MyArray(intLoop, 1)的第一个想法是好的 - 因为在这种情况下,不需要使用Transpose(因为它对数组中的元素数量有限制,所以并不总是有效):{ {1}}。但是我的代码几乎没有变化:

  • redim array as 2D:Range(...).Value = MyArray
  • 使用直接ReDim MyArray(1 To array_size, 1 To 1)

答案 1 :(得分:1)

Sub ListSheets()

' Defining all variables (objects) used within the code, establishing their
'classes

 Dim i As Integer
 Dim array_size As Integer
 Dim MyArray() As String

 array_size = 26
 ReDim MyArray(array_size) As String

 For intloop = 1 To 26
 MyArray(intloop) = Chr$(64 + intloop) + "6"
 Sheets(1).Range("A1").Offset(intloop - 1).Value = MyArray(intloop)
 Next
 'An array is not an object, you can't use SET with them.
 'Your array is 1-dimensional, MyArray(1,1) won't work as that's 2-dimensional, just
 'MyArray(1) = "whatever1"       MyArray(2) = "whatever2" etc. etc.
 End Sub