VBA中的动态For循环

凯特

作为VBA的新手,非常感谢您对以下问题的帮助。

我正在尝试创建一个0和1的表。我有一组变量,可以称它们为A,B,C,每个变量分别可以包含a,b,c个不同的值(a,b,c是整数)。我正在尝试构建这三个变量组合的所有不同情况的矩阵。矩阵中的值将为0或1。因此,如果a = 2,b = 3,c = 4,则表格将如下所示

样本矩阵

我已经编写了代码(在最后插入)。

但是,该表必须是动态的,因为变量的数量(以及每个变量的方案的数量)不是固定的。有人可以帮帮我吗?

谢谢

Sub table()
For i = 1 To 2
    For j = 1 To 3
        For k = 1 To 4
            For m = 1 To 9
                If m = i Then
                    Worksheets("sheet1").Range("a1").Cells(12 * (i - 1) + 4 * (j - 1) + k, m).Value = 1
                ElseIf m = j + 2 Then
                    Worksheets("sheet1").Range("a1").Cells(12 * (i - 1) + 4 * (j - 1) + k, m).Value = 1
                ElseIf m = k + 5 Then
                    Worksheets("sheet1").Range("a1").Cells(12 * (i - 1) + 4 * (j - 1) + k, m).Value = 1
                Else
                    Worksheets("sheet1").Range("a1").Cells(12 * (i - 1) + 4 * (j - 1) + k, m).Value = 0
                End If
            Next m
        Next k
    Next j
Next i
End Sub
斯科特·克莱纳(Scott Craner)

试试这个:

Sub matrix()
Dim arr() As Variant
Dim totrow As Long
Dim j As Long
Dim t As Long
Dim p As Long
Dim x As Long
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
'Set your array of numbers
arr = Array(2, 3, 4)
'If you want to refer to ranges on Sheet1 use:
'arr = Array(ws.Range("T1"), ws.Range("U1"), ws.Range("V1"))

totrow = 1
For j = LBound(arr) To UBound(arr)
    totrow = totrow * arr(j)
    x = x + arr(j)
Next j
ws.Range(ws.Cells(1, 1), ws.Cells(totrow, x)).Value = 0
p = 1

For j = UBound(arr) To LBound(arr) Step -1
    For t = 1 To totrow Step 1
        For i = 1 To arr(j)
            ws.Range(ws.Cells(t, x - arr(j) + i), ws.Cells(t + p - 1, x - arr(j) + i)).Value = 1
            t = t + p
        Next i
        t = t - 1
    Next t
    p = p * arr(j)
    x = x - arr(j)
Next j
End Sub

这将适用于数组中的任何值或数组中的任意数量的整数。主要限制是工作表上的行数和列数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章