复制一系列单元格并多次插入

时间:2017-07-14 14:46:08

标签: excel-vba vba excel

我有几百个具有唯一ID号的接线盒,它们都包含相同的部件,我需要创建一个列表,显示每个ID号下的部件列表。

我今天早上刚刚开始使用VBA并拼凑了一个零碎的宏。

宏执行以下操作: 提示用户选择要复制的单元格范围(变量cell_rng)。 提示用户选择一个单元格以开始插入复制的单元格的过程(变量start_cell)。 提示用户输入复制范围应输入的次数变量j)(总数    JBS)。 提示用户输入要复制的单元格区域中包含的行数(变量k)。

宏应该在原始列表的每一行(接线盒ID)之间插入cell_rng。 它应该开始在start_cell下面插入cell_rng,然后在start_cell下面插入cell_rng k行(k是复制的行数,因此列表中下一个接线盒ID下面的单元格的新位置),然后是k行在start_cell下面x 1,然后在start_cell下面k行x 2,依此类推,直到达到数字j。

然而宏所做的是将cell_rng插入start_cell下面,然后在第一个cell_rng插入下面插入cell_rng k + 1 行**。 因此,如果k = 5且start_cell = 1,则宏将从单元格2开始插入cell_rng,单元格7到11将没有插入,并且该过程将在单元格9上再次开始。 然后它继续工作,因为我希望它能够将cell_rng插入到应该的位置。

是否有人能够帮助我让宏在原始列表的每一行之后插入cell_rng? 如果解释难以理解,请写下来,写下你想要宏做的事情并不容易!

宏的代码如下。

Sub Insert_Copied_Cells()
'
'Insert_Copied_Cells
'This Macro copies a range of cells and inserts x number of times below a             
 specified cell.
'The offset can be altered so that a copied range can be inserterd on 
 multiple lines without changed data already present.
'
'This marco misses the first 6 row for some reason, this needs to be 
corrected somehow..........

'
Dim i As Variant, j As Variant, k As Variant, l As Variant, cell_rng As 
Range, start_cell As Range
'i = number of repeated entries required
'j = number of repeated entries required
'k = number of rows in the range of cells to be copied
'l = number of repeated entries required
'cell_rng = range of cells to be copied
'start_cell = the cell below which the copied range should be inserted, this 
'is the reference cell for all the repetition of the range insertion

 Set cell_rng = Application.InputBox("Select Range to be Copied", "Obtain 
 Range", Type:=8)
 'promts user to select a range to be copied

 Set start_cell = Application.InputBox("Select the First Cell Below Which 
 Copied Range will be Entered", "Obtain Starting Cell", Type:=8)
 'promts user to select a cell to start the process

  j = InputBox("Input Number of Entry Repetitions Required")
 'prompts user to enter number of repeated entries required

  k = InputBox("Number of rows to be Copied")
 'prompts user to enter number of rows the selected range contains

  l = k + 1
 'adds one onto number of rows to be copied to allow for next entry

 For i = 0 To j
 'run through the code below from i= 0 increasing by 1 until number j is reached, then stop.

  cell_rng.Select
 'defines the range to select (range defined above at prompt)
  Selection.Copy
 'copies the range of cells
  start_cell.Offset((l * i), 0).Select
'selects starting cell to paste range into
  Selection.Insert Shift:=xlDown
'inserts the selected range below the starting cell

 Next i


End Sub

1 个答案:

答案 0 :(得分:0)

我相信这一切都在你的起点。 您应该插入A2,A8,A14,A20,A26等。 如果每个JBox包含相同的信息,为什么不设置k = 5,并且l = 6? start_cell应该是2.你的偏移量从0,0(6x0)开始,然后是6,0(6x1), 那么12,0(6x2)等等,这似乎没问题。我自己也是业余爱好者,我确信还有很多其他方法可以完成你正在做的事情,但我认为只需要做一次就能完成任务(只是猜测)。希望这有点帮助或让你朝着正确的方向前进。

@teylyn查看类似问题的答案。用于插入行的非常简单的编码。很干净!!

https://stackoverflow.com/a/36639509/7793894