如何根据另一个表中的2个值在Excel中创建表

时间:2017-04-18 20:21:59

标签: excel

您好我想基于另一个表中的2个值在表中生成值。用文字解释这个问题很难,所以我试着用一个例子来解释它。 示例:表1中的数据需要用于填充表2中的值

表1:

Building type             Number
Hospital                     4           
Fire station                 2
Hotel.                       0

表2

Hospital 1
Hospital 2
Hospital  3
Hospital  4
Fire station 1
Fire station 2

请注意,如果表1的第2列中的数字为0,则表2中不应创建相应的值。

1 个答案:

答案 0 :(得分:0)

您可以使用某些VBA快速完成此操作:

Sub makenewtable()
    Dim rngTable1 As Range
    Dim rngTable2 As Range
    Dim rngReadRow As Range
    Dim intWriteRow As Integer
    Dim intLoop As Integer

    'set this to your first table
    Set rngTable1 = Sheet1.Range("A2:B4")

    'set this to the first row to write to:
    Set rngTable2 = Sheet2.Range("A2")
    rngWriteRow = 0

    'Loop through the first table row by row
    For Each rngReadRow In rngTable1.Rows
        'Loop the number of times the first table says we should
        For intLoop = 1 To rngReadRow.Cells(1, 2).Value
            'write the value out to the second table
            rngTable2.Offset(rngWriteRow, 0) = rngReadRow.Cells(1, 1).Value
            rngTable2.Offset(rngWriteRow, 1) = intLoop

            'increment the row to which we are writing
            rngWriteRow = rngWriteRow + 1
        Next
    Next rngReadRow

End Sub