简体   繁体   中英

Excel: Automate copying a value a number of times equivalent to the Count of non-zero cells in the same row

As my dataset is quite large (thousands of rows and dozens of columns), I would like to automate the process of:

  1. copying a given ID# a number of times equivalent to the Count of non-zero cells (parents) in its row (excluding the ID# itself), and
  2. adding the parent# in question to a cell adjacent to the copied ID#.
  3. Ignore all parents with cells equal to zero.

Example:

My dataset possesses ID numbers in Column A. Each ID# possesses multiple parents in its own row. ID# 1 in Cell A2 possesses 4x nonzero parent numbers 265, 266, 32 and 7, in B2, C2, D2 and E2 respectively. Cell F2 = zero, and should be ignored.

当前数据格式:每个ID#的父母

Desired output in another sheet:

在此处输入图片说明

Any help would be greatly appreciated. Thank you!

This will do what you want.

Change the sheet names to match the sheet names you have.

Sub Sortstuff()

Dim ows As Worksheet
Dim tws As Worksheet
Dim trw&
Dim cel as range

Set ows = Worksheets("Sheet1") 'original sheet
Set tws = Worksheets("Sheet2") 'target sheet

For Each cel In ows.Range(ows.Range("B2"), ows.Range("B2").End(xlDown).End(xltoRight))
    If cel <> 0 Then
        trw = tws.Range("A" & tws.Rows.count).End(xlUp).Offset(1).Row
        tws.Cells(trw, 2) = ows.Cells(cel.Row, 1)
        tws.Cells(trw, 1) = cel.value
    End If
Next

End Sub

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