How to insert 'n' number of rows based on 'n' being a number in a cell

青春壹個敷衍的年華 提交于 2021-01-29 02:31:05

问题


I have a list of companies in column a. In column b, I have a number. I need to create a list where the company appears as many times in the list as the value of the number:

Company A    4
Company B    2
Company C    3  

I want:

Company A
Company A
Company A
Company A
Company B
Company B
Company C
Company C
Company C  

So, it's sort of a 'Create (n) Duplicates' function.


回答1:


Give this a try:

Sub KopyKat()
   Dim N As Long, i As Long, K As Long
   Dim v As String, kk As Long, m As Long
   N = Cells(Rows.Count, "B").End(xlUp).Row
   K = 1

   For i = 1 To N
      kk = Cells(i, "B").Value
      v = Cells(i, "A").Value
      For m = 1 To kk
         Cells(K, "C") = v
         K = K + 1
      Next m
   Next i
End Sub

EDIT#1:

Macros are very easy to install and use:

  1. ALT-F11 brings up the VBE window
  2. ALT-I ALT-M opens a fresh module
  3. paste the stuff in and close the VBE window

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE window as above
  2. clear the code out
  3. close the VBE window

To use the macro from Excel:

  1. ALT-F8
  2. Select the macro
  3. Touch RUN

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

Macros must be enabled for this to work!




回答2:


I am not sure this really all that easy / feasible to do just formulas or manual Excel functions, based on your list, so here is VBA procedure to do the job.

To use this click Alt + F11 inside of Excel. Go to Insert > Module. Then paste it in the module and run it (after adjusting for data ranges and sheet names.

Sub MakeList()

Dim ws As Worksheet
Set ws = Sheets("Sheet1") 'change to your sheet name

With ws

   Dim c As Range
   For Each c In .Range("A1:A3") ' assumes list in cells A1-B3
        .Range("D" & .Rows.Count).End(xlUp).Resize(c.Offset(, 1)).Value = c.Value 'builds list in column C
   Next

End With


End Sub


来源:https://stackoverflow.com/questions/33288517/how-to-insert-n-number-of-rows-based-on-n-being-a-number-in-a-cell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!