生成0和1的组合

时间:2018-05-28 14:08:08

标签: excel vba excel-vba

我有两排单元格:A1,B1,C1和A2,B2,C2。在这两行中的每一行中,只能有一个1,其他两个单元格设置为0.以下是一个示例:

    A   B   C
  +---+---+---+
1 | 1 | 0 | 0 |
  +---+---+---+
2 | 0 | 1 | 0 |
  +---+---+---+

我正在尝试迭代所有9种可能的组合:第一行有3种可能性,第二种有3种可能性。我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

这是一种方式:

Function delta(i As Long, n As Long) As Variant
    'returns an array of length n
    'consisting of all 0 with one 1
    'at index i
    Dim A As Variant
    ReDim A(1 To n) As Long
    A(i) = 1
    delta = A
End Function

Sub IterateOver()
    Dim i As Long, j As Long
    For i = 1 To 3
        Range("A1:C1").Value = delta(i, 3)
        For j = 1 To 3
            Range("A2:C2").Value = delta(j, 3)
            'stub for real code:
            MsgBox "Continue?", vbQuestion, "Test"
        Next j
    Next i
End Sub

答案 1 :(得分:0)

这将为3列

生成01的所有8种组合
Dim i As Integer

For i = 1 To 2^3
    Range("A" & i) = (i-1) % 2
    Range("B" & i) = Int((Range("A" & i))/2) % 2
    Range("C" & i) = Int((Range("B" & i))/2) % 2
Next i

尝试自己扩展