vba 根据单元格值插入行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45262303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert row based on cell value
提问by Faheera
I am new to macro Excel functions and I am trying to insert a row when there is a change in the cell value of a particular column. For example,
我是宏 Excel 函数的新手,当特定列的单元格值发生变化时,我试图插入一行。例如,
row_no B
1 p
2 p
3 p
4 q
5 q
6 q
7 q
A row should be inserted at row 3 as the value in column 1 has changed. Do you have any ideas?
由于第 1 列中的值已更改,因此应在第 3 行插入一行。你有什么想法?
Right now, this is my code.
现在,这是我的代码。
Sub MySub()
Do While B1 <> B2
CurrentSheet.Range("a1:i1").EntireRow.Insert
Loop
End Sub
It is still not working, do all of you have any idea why?
它仍然无法正常工作,你们所有人都知道为什么吗?
采纳答案by Mrig
Try this code:
试试这个代码:
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
回答by ViperSRT3g
Insert the following into your Sheet1 (Sheet1)VBA module (Or the module that pertains to the worksheet you want this functionality in)
将以下内容插入您的Sheet1 (Sheet1)VBA 模块(或与您想要此功能的工作表相关的模块)
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
This inserts a row below the changed cell if that cell's column number is column 1 or A
如果该单元格的列号是第 1 列或A,这将在更改的单元格下方插入一行