最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vba - Excel fill numbers within a range - Stack Overflow

programmeradmin1浏览0评论

I’m trying to find a way to get numbers within a range. I have the minimum and maximum of the range and I want to insert the numbers in between the ranges. Instead of entering the numbers manually, is there a way I can automate this?

Example and outcome pictures attached:

I’m trying to find a way to get numbers within a range. I have the minimum and maximum of the range and I want to insert the numbers in between the ranges. Instead of entering the numbers manually, is there a way I can automate this?

Example and outcome pictures attached:

Share Improve this question edited Jan 21 at 14:07 Dominique 17.6k19 gold badges78 silver badges148 bronze badges asked Jan 21 at 11:49 AragogAragog 35 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Pls try

Option Explicit

Sub Demo()
    Const OUTPUT_CELL = "D1" ' Start cell of output
    Dim i As Long, j As Long
    Dim arrData, rngData As Range
    Dim arrRes, iR As Long
    Dim LastRow As Long
    Dim oSht1 As Worksheet: Set oSht1 = Sheets("Sheet1")
    Set rngData = oSht1.Range("A1").CurrentRegion
    ' load table into an array
    arrData = rngData.Value
    With Application
        ReDim arrRes(.Max(rngData) - .Min(rngData) + 1, 0)
    End With
    ' header of output
    arrRes(0, 0) = "Output"
    ' populate output array
    For i = LBound(arrData) + 1 To UBound(arrData)
        For j = arrData(i, 1) To arrData(i, 2)
            iR = iR + 1
            arrRes(iR, 0) = j
        Next j
    Next i
    ' write output to sheets
    oSht1.Range(OUTPUT_CELL).Resize(iR + 1, 1).Value = arrRes
End Sub

Microsoft documentation:

Range.Resize property (Excel)

Range.CurrentRegion property (Excel)

Do you have the Sequence() worksheet function on your computer? This gives you the possibility to do this without VBA, using the formula =Sequence(C2-B2+1;1;B2;1):

Explanation of the parameters:

  • C2-B2+1 : the amount of entries (rows) you need is 9 (=10-2+1).
  • 1 : everything in one column.
  • B2 : you start by the value in "B2".
  • 1 : you increase by one.
发布评论

评论列表(0)

  1. 暂无评论