问题
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:
- ALT-F11 brings up the VBE window
- ALT-I ALT-M opens a fresh module
- 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:
- bring up the VBE window as above
- clear the code out
- close the VBE window
To use the macro from Excel:
- ALT-F8
- Select the macro
- 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