使用Vba在一个单元格中生成等距的数字序列

时间:2016-10-21 04:14:02

标签: arrays excel vba excel-formula

示例:

A    B    C         D
Min Max Steps   Result
10  70   4      10,30,50,70
30  150  5      30,60,150,90,120   
40  100  2      40,100    
50  150  3      50,100,150   
60  160  6      60,80,140,100,120,160 
120 160  3      120,140,160

我想在D2中生成结果,这是"数字的等距序列" (例如" 10,30,50,70")基于A2中的Min,B2中的Max和C2中的步骤(该序列中的单位计数)。然后是整列D

我当前的方法是计算其他工作表中每个单元的值,并使用Concatenate()函数将它们合并到D列中

我可以用vba改进它吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

此功能将执行

Function EquidistanceSequence(min As Long, max As Long, steps As Long) As String
    Dim i As Long
    For i = min To max Step steps
        EquidistanceSequence = EquidistanceSequence & i & ","
    Next i
    EquidistanceSequence = Left(EquidistanceSequence, Len(EquidistanceSequence) - 1)
End Function

由主要子类使用:

Sub main()
    With Worksheets("MyDataSheet") '<-- change "MyDataSheet" to your actual sheet name from which read input data from
        MsgBox EquidistanceSequence(.Range("A2").Value, .Range("B2").Value, .Range("C2").Value)
    End With
End Sub

或:

Sub main()
    MsgBox EquidistanceSequence(10, 70, 20)
End Sub

或直接在您的Excel工具栏中输入任意单元格:

=EquidistanceSequence(A2;B2;C2)