使用 Excel 中的 vba 为行 x 列设计填充 table

Populating a table for a row x column design using vba in Excel

我是在 excel 中创建 VBA 的新手。因此,我在基础知识上苦苦挣扎。我想创建一个 VBA 来填充与逐列统计设计相关的 table。例如,如果要为具有 2 行和 3 列的逐列设计生成 table,我的 table 将如下所示:

或者如果我想使用 VBA 为 3 x 2 行按列设计创建 table,table 将如下所示:

等等

有人可以帮我开发一个简单的 VBA,我可以在其中选择布局的行数和列数,然后使用 VBA 生成相应的 table 吗?

试试代码:

Sub Test()

    Dim x As Long
    Dim y As Long
    Dim a() As Long
    Dim i As Long

    x = 2 ' columns
    y = 3 ' rows
    ReDim a(1 To x * y, 1 To 2)
    For i = 0 To x * y - 1
        a(i + 1, 1) = i Mod y + 1
        a(i + 1, 2) = i \ y + 1
    Next
    ThisWorkbook.Sheets(1).Cells(1, 1).Resize(x * y, 2).Value = a

End Sub

您需要遍历行和列以创建 table。

我的意思是:

Dim row As Long
Dim column As Long
Dim end_row As Long
Dim end_col As Long
Dim wb As Workbook
Dim ws As Worksheet
'Dim index As Long

Set wb = Excel.Application.ThisWorkbook
Set ws = wb.Worksheet("worksheet name")

'alternatively, you can do this too if you prefer to use numbers
'Set ws = wb.Worksheet(index)

end_row = 3
end_col = 2

'this loop iterates over rows
For row = 1 To end_row
    'this loop iterates over columns
    For column = 1 To end_col
        'sets headers
        If row = 1 Then
            ws.Cells(row, 1).Value = "Column 1"
            ws.Cells(row, 2).Value = "Column 2"
        'puts row numbers in column 1
        ElseIf row > 1 Then
            ws.Cells(row, 1).Value = row
        End If 
            'puts column numbers in row 2
            ws.Cells(2, column).Value = column
    Next
Next

希望对您有所帮助!