数组不从For循环VBA填充

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

然而数组

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 

有任何想法吗?

提前谢谢了。

试试这个:

 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 (它并不总是工作,因为它对数组元素的数量有限制): Range(...).Value = MyArray 。 不过,我已经对你的代码做了一些改变:

  • redim数组为2D: ReDim MyArray(1 To array_size, 1 To 1)
  • 使用直接Range(...).Value = MyArray
 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