Domanda

I have an ID column (A) and a column of variable data (B) as shown below.

    A    B
    1    0.1
    2    0.1
    3    0.1
    4    0.2
    5    0.3
    6    0.3
    7    0.2
    8    0.3

I need to generate a VBA code which groups this data so that the summary table would look like this:

    Start ID    End ID    B Value
    1           3         0.1
    4           4         0.2
    5           6         0.3
    7           7         0.2
    8           8         0.3

I am fairly new to Excel VBA and am having trouble writing a short code which can do this. The data I have included is also just the first part of the sample, the code needs to be able to create a summary for any number of IDs. Any help is much appreciated, Thanks.

È stato utile?

Soluzione

This code is somewhat ugly and dirtily put together, but it'll do the trick:

(ASSUMPTIONS:

  • Your values start in Cell B2 and their corresponding IDs start in A2
  • Your Summary Table starts in E2
  • You have less than 50 rows to your dataset

Change everything as you need)

    Sub CreateSummaryTable()

    Dim cl As Range
    Dim StartCl As Range
    Dim TableRow As Integer

    Set StartCl = Range("B2")
    TableRow = 2

    For Each cl In Range("B2:B50")
        If cl.Value <> StartCl.Value Then
            Range("E" & TableRow).Value = StartCl.Offset(0, -1).Value
            Range("F" & TableRow).Value = cl.Offset(-1, -1).Value
            Range("G" & TableRow).Value = StartCl.Value

            Set StartCl = cl
            TableRow = TableRow + 1
        End If
    Next

    End Sub
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top