有没有一种方法可以基于数组“ x”的次数填充Excel中的单元格

时间:2020-07-29 10:16:51

标签: excel vba loops foreach

我正在尝试创建VBA脚本,以基于数组X次填充Excel中的单元格。 目标是先填充第一个数组值50次,然后填充下一个数组值50次,依此类推。 目前,我设法使用下面的代码来完成此工作,但是它仅填充一个单元格,并且将转到下一个单元格。 有谁知道如何更新此代码,并使其以“ 55”填充50个单元格,然后以“ 66”填充50个单元格? 预先感谢!


Sub StaticArrayTest()
    Dim Myarray(1 To 3) As Integer
    Dim i As Integer
    
    Myarray(1) = 55
    Myarray(2) = 66
    Myarray(3) = 77
    
    For i = 1 To UBound(Myarray)
        Cells(i, 1).Value = Myarray(i)
    Next i

End Sub

4 个答案:

答案 0 :(得分:2)

有趣的小选择:

Sub Test()  
    Range("A1:A150").Value = [CHOOSE(ROUNDUP(ROW(1:150)/50,0),55,66,77)]
End Sub

注意:不要被短短的写作所骗。它可能更难以维护且运行时间更长。只是通过=)抛出另一个选项

答案 1 :(得分:1)

这应该可以解决问题。您还需要几个变量来跟踪单元格的位置并循环遍历每个值的迭代:

Option Explicit
Sub StaticArrayTest()

    Dim Myarray(1 To 3) As Long 'Never use integer in Excel
    Myarray(1) = 55
    Myarray(2) = 66
    Myarray(3) = 77
    
    Dim NumberOfIterations As Long: NumberOfIterations = 50
    Dim i As Long, j As Long
    Dim Position As Long: Position = 1
    For i = 1 To UBound(Myarray)
        For j = 1 To NumberOfIterations
            Cells(Position, 1) = Myarray(i)
            Position = Position + 1
        Next j
    Next i

End Sub

答案 2 :(得分:1)

我会略有不同。

我将创建一个新数组来保存所有值,然后将其一键式写入工作表。这样的事情。它还使您可以轻松灵活地更改值。

Option Explicit

Sub StaticArrayTest()
    Dim Myarray(1 To 3) As Long
    Myarray(1) = 55
    Myarray(2) = 66
    Myarray(3) = 77
    
    '~~> Number of iterations
    Dim slots As Long
    slots = 50
    
    '~~> Final array to hold values
    Dim finalArray() As Long
    ReDim finalArray(1 To slots * UBound(Myarray))
    
    Dim i As Long, j As Long, k As Long
    k = 1
    
    '~~> Populate the array
    For i = LBound(Myarray) To UBound(Myarray)
        For j = 1 To slots
            finalArray(k) = Myarray(i)
            k = k + 1
        Next j
    Next i
    
    Dim ws As Worksheet
    Set ws = Sheet1
    
    '~~> Write to the sheet in 1 go
    ws.Range("A1").Resize(UBound(finalArray), 1).Value = _
    WorksheetFunction.Transpose(finalArray)
End Sub

答案 3 :(得分:1)

更接近OP的方法...

您的主要问题是,您只填充了一个行范围就遍历了三个数组项;定义具有给定偏移量的起始范围将成功,并可以减少循环周期:

Sub StaticArrayTestMe()
    '~~> Number of iterations
    Const slots As Long = 50
    '~~> values to insert repeatedly
    Dim Myarray(1 To 3) As Long
    Myarray(1) = 55
    Myarray(2) = 66
    Myarray(3) = 77
    
    With Sheet1.Range("A1:A" & slots)            ' refer to start range of 50 cells using the sheet's Code(Name)
        Dim i As Long
        For i = LBound(Myarray) To UBound(Myarray) ' here: 1st item to 3rd item
            'calculate new row offsets to start range: (1) 0, (2) 50, (3) 100
            .Offset((i - 1) * slots) = Myarray(i)  ' fill in 1st,2nd & 3rd item
        Next i
    End With
End Sub