根据单元格值插入行

我是新的macrosExcelfunction,我想插入一个特定的列的单元格值发生变化时行。 例如,

row_no B 1 p 2 p 3 p 4 q 5 q 6 q 7 q 

当行1中的值已经改变时,行3应该被插入。 你有什么想法?

现在,这是我的代码。

  Sub MySub() Do While B1 <> B2 CurrentSheet.Range("a1:i1").EntireRow.Insert Loop End Sub 

它仍然没有工作,你们都有什么想法吗?

试试这个代码:

 Sub Demo() Dim ws As Worksheet Dim lastRow As Long, i As Long Set ws = ThisWorkbook.Sheets("Sheet1") 'set you data sheet here lastRow = Cells(Rows.Count, "A").End(xlUp).Row 'get the last row in column A For i = lastRow To 2 Step -1 'loop from last row to row 2 If ws.Range("A" & i) <> ws.Range("A" & i - 1) Then 'compare value if not same ws.Range("A" & i).EntireRow.Insert 'if value are not same insert row End If Next i End Sub 

将以下内容插入Sheet1(Sheet1) VBA模块(或与您需要此function的工作表相关的模块)

 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Application.EnableEvents = False If Target.Column = 1 Then Rows(Target.Row + 1).EntireRow.Insert Application.EnableEvents = True End Sub 

如果该单元格的列号是列1或A,则在已更改的单元格下插入一行