简体   繁体   中英

Split list with vba based on category

I have one flat excel list with data that can be split into three categories (projects, activities and initiatives)

With vba i want to split the list so it first shows the projects, then a line break with repetition of the header with displaying the activities, then a line break with repetition of the header with displaying the initiatives all in 1 worksheet

Example

Description   Type 
Project a       project 
Project b       project
Maintenance a   activity
Project c       project
Initiative 1    initiative

To be split into

Description Type 
Project a       project
Project b       project
Project c       project

Description     Type
Maintenance a  activity  

Description           Type
Initiative 1    initiative

is there any VBA code to achieve this?

regards Geert

This requires a simple looping function that checks for the item type and writes it into the other sheet. Assuming Sheet1 is where the original list is and Sheet2 is where the new list will be, you could implement a function somewhat like the following. You can get the number of rows by using a worksheet function like counta on the first column. This function you would run within your main subroutine, inputting "project", "activity", etc. for the ItemType. For the counter, you can take the return value of CopyVals and feed it back in through each time.

Function CopyVals(ItemType As String, counter As Integer)
    For j = 2 To numRows + 1
        Sheet2.Cells(counter, 1) = Sheet1.Cells(1, 1)     'Write a header line
        Sheet2.Cells(counter, 2) = Sheet1.Cells(1, 2)
        counter = counter + 1
        If Sheet1.Cells(j, 2) = ItemType Then             'Copy items into new list
            Sheet2.Cells(counter, 1) = Sheet1.Cells(j, 1)
            Sheet2.Cells(counter, 2) = Sheet1.Cells(j, 2)
            counter = counter + 1
        End If
    Next j
    counter = counter + 1                                 'Blank line in between
    CopyVals = counter                                    'Return counter value
End Function

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