我试图在VBA代码中创建一个包含2行和5列的数组。可能吗?我这样写了
Sub robin()
Cells.Select 'this codes clears previous entries
Range("T17").Activate
Selection.ClearContents
Range("E4").Select
Dim myArray(1, 4) As Double
Dim a As Double, b As Double
Dim i As Integer
Dim j As Integer
Dim c As Double
c = 1
For a = 0 To UBound(myArray())
For b = 0 To UBound(myArray())
myArray(a, b) = c
ThisWorkbook.Sheets("Sheet1").Cells(a + 1, b + 1).Value = myArray(a, b)
c = c + 1
Next b
Next a
End Sub
但它有两行两列。怎么办?
答案 0 :(得分:0)
默认情况下,UBound将返回数组第一维的最高索引。您需要将可选参数设置为2以获取第二维的最后一个索引。
For b = 0 To UBound(myArray(), 2)
答案 1 :(得分:0)
Sub batman()
[Sheet1!A1:E2] = [{1,2,3,4,5;6,7,8,9,10}]
End Sub
或
Sub robin()
Dim myArray(1 To 2, 1 To 5) As Double, c As Long
For c = 1 To 5
myArray(1, c) = c
myArray(2, c) = c + 5
Next
[Sheet1!A1:E2] = myArray
End Sub
答案 2 :(得分:0)
感谢你们所有人的时间。我已经找到了获得我想要的东西的方法。我重写了这样的代码:
Sub robin()
Cells.Select 'this codes clears previous entries
Range("T17").Activate
Selection.ClearContents
Range("E4").Select
Dim myArray(1, 5) As Double
Dim a As Double, b As Double
Dim i As Integer
Dim j As Integer
Dim c As Double
c = 1
For a = LBound(myArray, 1) To UBound(myArray, 1)
For b = LBound(myArray, 2) To UBound(myArray, 2)
myArray(a, b) = c
ThisWorkbook.Sheets("Sheet1").Cells(a + 1, b + 1).Value = myArray(a, b)
c = c + 1
Next b
Next a
End Sub
这对我来说非常合适。再次感谢。