在插入的行中复制数据

时间:2016-05-06 20:05:33

标签: vba excel-vba excel

下面的代码自动在Excel工作表中插入指定的行,我需要此代码也只复制上一行插入行中某些单元格的数据。换句话说,在数据(附加图像)中,下面的代码在活动单元格上方添加空行。我还需要的是将列Sales_IDSales_market中的数据复制到插入行中的代码。

Screenshot of Worksheet

e.g。如果我在客户4上方添加行(在数据中以黄色突出显示),则代码会将Sales_ID 1234Sales_market Canada复制到插入的行中。 Customers中的其他单元格和插入行中的Customer_ID应为空白。

Sub Multiplerows4()
  Dim rng As Integer
  Dim k As Integer
  Dim rRange As Range

  Set rRange = Selection

  rng = InputBox("Enter number:.")
  For k = 1 To rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
      CopyOrigin:=xlFormatFromLeftOrAbove
  Next
End Sub

2 个答案:

答案 0 :(得分:1)

考虑添加第二个向后步进循环来更新插入的行。以下假定Sales_IDSales_Market位于第一列和第二列(相应调整):

Sub Multiplerows4()
    Dim rng As Integer, k As Integer
    Dim rRange As Range
    Dim salesID As Long, salesMkt As String

    Set rRange = Selected

    salesID = Cells(rRange.Row, 1)
    salesMkt = Cells(rRange.Row, 2)

    rng = InputBox("Enter number:.")
    For k = 1 To rng
        Rows(rRange.Row).Insert Shift:=xlDown, _
                                CopyOrigin:=xlFormatFromLeftOrAbove
    Next k

    For k = rng To 1 Step -1
        Cells(rRange.Row - k, 1) = salesID
        Cells(rRange.Row - k, 2) = salesMkt
    Next k

End Sub

答案 1 :(得分:0)

以下是Parfait帮助下修改后的代码版本,该版本适用于我的目的 -

Sub Multiplerows()
Dim rng As Integer, k As Integer
Dim rRange As Range
Dim salesID As Long, salesMkt As String

Set rRange = Selection
rng = InputBox("Enter number:.")
For k = 1 To rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
                            CopyOrigin:=xlFormatFromLeftOrAbove
Next k
   For k = rng To 1 Step -1
Cells(rRange.Row - k, 1) = Cells(rRange.Row, 1)
Cells(rRange.Row - k, 2) = Cells(rRange.Row, 2)
   Next k
End Sub