根据单元格值插入单元格

我在这里find了这个脚本,并修改了一些以适应我的需要。 但是,我不知道如何插入一个单元而不是整个行

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 

任何帮助将不胜感激!

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

你将需要改变你的循环:

 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 

所以在使用之前确保你的数据是合理的。