首页 文章

Excel功能根据单元格值重复一组单元格一定次数

提问于
浏览
1

我正在寻找一种方法,在移动到下一组单元格之前,水平重复一组单元格一定次数 . 例如:

如果我在3列中有这个:

5   4   3
0   1   2

我有3列指示我希望迭代值的次数:

4   2   3

当拖动范围时,此函数应该给我这个:

5   5   5   5   4   4   3   3   3
0   0   0   0   1   1   2   2   2

有谁知道这样做的最佳方式?

我一直在使用一些复杂的推理来解决这个问题,使用数组公式(在它周围有“{}”括号,你必须使用Shift Enter) . 我使用SUMIF和COUNTIF函数来做一些事情,但它从来没有真正成功 .

1 回答

  • 0

    这是一个hacky VBA解决方案 . 这假设“重复计数”在第一行(4,2,3),“重复值”在第二行(5,4,3,0,1,2) .

    Sub outputRepeatedValues()
        Dim xStart As Integer, yStart As Integer
        Dim i As Integer, j As Integer
        Dim valueToRepeat As Integer, numTimesRepeat As Integer
        Dim xOffset As Integer, yOffset As Integer
    
        xStart = ActiveCell.Column
        yStart = ActiveCell.Row
    
        i = 1
        j = 1
        xOffset = 0
        yOffset = 0
    
        While Cells(2, j) <> ""
            If Cells(1, i) = "" Then
                i = 1
                yOffset = yOffset + 1
                xOffset = 0
            End If
    
            numTimesRepeat = Cells(1, i)
            valueToRepeat = Cells(2, j)
    
            For k = 1 To numTimesRepeat
                Cells(yStart + yOffset, xStart + xOffset) = valueToRepeat
                xOffset = xOffset + 1
            Next k
    
            j = j + 1
            i = i + 1
        Wend
    
    End Sub
    

    坚持这个新模块 . 要使用此代码,请选择表示输出区域左上角的单元格 . 然后按Alt F8以显示宏框,然后您可以运行宏 .

相关问题