简体   繁体   中英

build excel array from data items and a multiplier

first question on this site.

Been coming here to bask in the warm glow of the knowledge on offer for years! Please be gentle with me. ;)

I'm not a programmer but can muddle my way around excel but I have a problem in excel that I'm struggling to find a solution to.

I need to take a set of data and turn it into an array (or list) of all the occurrences of that data. For example a set of data (A,B,C) and an instances value for each item (2,1,3).

What I need to do is take those two items and create an array of all occurrences.

Like this:-

Data,Instances

A,2
B,1
C,3
Total 6

Result
1,A
2,B
3,C
4,A
5,C
6,C

(I hope that's clear - my rating isn't high enough to post a screenshot)

So, in this example I have 2 As, 1 B and 3 Cs giving a total of 6 items. To create the result I've run through the list 6 times listing each data item if it still has an occurrence (but an array/list that was AABCCC would be just as valid). For the full data set there could be as many as 12 different data items with any number of occurrences each from 1 to 12.

Somehow I think I'm overcomplicating a simple process but for the life of me I can't get my head around achieving the result I need.

Say we put your data in column A :

在此处输入图片说明

and run this short macro:

Sub croupier()
    Dim N As Long, K As Long, i As Long, ary(), bry()
    Dim v As String
    N = Cells(Rows.Count, "A").End(xlUp).Row
    ReDim ary(1 To N)
    ReDim bry(1 To N)

    For i = 1 To N
        v = Cells(i, "A").Value
        cry = Split(v, ",")
        ary(i) = cry(0)
        bry(i) = CLng(cry(1))
    Next i

    K = 1
    While Application.WorksheetFunction.Sum(bry) > 0
        For i = 1 To N
            If bry(i) <> 0 Then
                Cells(K, "B").Value = ary(i)
                bry(i) = bry(i) - 1
                K = K + 1
            End If
        Next i
    Wend
End Sub

Our result is this:

在此处输入图片说明

We repeatedly run down column A placing the values in column B until the count of an item reaches zero.

When the overall count of items is zero, we stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM