根据单元格值在上面插入单元格

时间:2016-12-05 19:56:47

标签: excel vba excel-vba insert copy

我在这里找到了这个脚本并修改了一些以满足我的需求。但是,我无法弄清楚如何插入一个单元格而不是整行

Sub BlankLine()
  Dim Col As Variant
  Dim Col2 As Variant
  Dim BlankRows As Long
  Dim LastRow As Long
  Dim R As Long
  Dim StartRow As Long

  Col = "A"
  Col2 = "B"
  StartRow = 2
  BlankRows = 1

  LastRow = Cells(Rows.Count, Col).End(xlUp).Row

  Application.ScreenUpdating = False

  With ActiveSheet
    For R = LastRow To StartRow + 1 Step -1
      If .Cells(R, Col) <> .Cells(R, Col2) Then
        .Cells(R, Col2).EntireRow.Insert Shift:=xlUp
      End If
    Next R
  End With Application.ScreenUpdating = True
End Sub

因此,如果列A与任何给定行的列B不匹配,则插入一个空格,然后继续比较,在任何假值之上添加一行。

Example: 1 1
         2 3
         3 4

Becomes: 1 1
         2
         3 3
           4 

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

.Cells(R, Col2).Insert Shift:=xlDown

答案 1 :(得分:0)

您需要更改循环:

For R = LastRow To StartRow + 1 Step -1
    If .Cells(R, Col) <> .Cells(R, Col2) Then
       .Cells(R, Col2).EntireRow.Insert Shift:=xlUp
    End If
Next R

For R = StartRow To LastRow
    If .Cells(R, Col).Value <> .Cells(R, Col2).Value Then
        .Cells(R, Col2).Insert Shift:=xlDown
    End If
Next R

警告 - 如果您的数据如下:

Example: 1 3
         2 1
         3 2

它最终看起来像这样:

Becomes: 1 
         2
         3 3
           1
           2

因此在使用之前请确保您的数据处于合理的序列中。