通过循环随机填充列

时间:2019-10-04 17:34:18

标签: excel vba loops

最近,我得到了一个基于行#1值随机填充单元格的代码的帮助。 Answered_Post。 (感谢@JvdV和@Scott Craner之前为我提供的帮助。)

我现在需要做的几乎是相同的,但是代码将按照随机值(x)填充总共10行中跨越列的单元格。可重复的值保留在第1行上。

在该帖子提供的代码下方填充行。我现在需要按照图片填充各列。

Dim x As Long, y As Long, z As Long
With Sheet1 'Change accordingly
For y = 1 To 15
    z = 0
    Do While z < 4
        x = Int((7 - 2 + 1) * Rnd + 2)
        If .Cells(x, y) <> .Cells(1, y) Then
            .Cells(x, y) = .Cells(1, y)
            z = z + 1
        End If
    Loop
Next y
End With

Table_With_Sample_Values

1 个答案:

答案 0 :(得分:-1)

Sub FillColumns01()
    For y = 1 To 15
    z = 0
    j = 1
    Do While z < 4
            x = Int((7 - 2 + 1) * Rnd + 2)
            If Cells(x, y) <> Cells(1, y) Then
                Cells(y + 1, j) = Cells(1, y)
                z = z + 1
                j = j + 1
            End If
    Loop
Next y
End Sub

Sub FillColumns02()
'Using a 3rd Loop
Dim x As Integer, y As Integer, z As Integer, j As Integer

For y = 1 To 10
    z = 0
    Do While z < 4
        For j = 1 To 15
            x = Int((7 - 2 + 1) * Rnd + 2)
            If Cells(x, y) <> Cells(1, y) Then
                Cells(j, x) = Cells(1, y)
                z = z + 1
            End If
        Next j
    Loop
Next y

End Sub