[英]Delete specific rows in Excel sheet
I have a table with multiple columns.我有一个多列的表。 I would like to delete specific rows within the table.
我想删除表中的特定行。 The logic to delete is the following:
删除逻辑如下:
If in column B one cell contains a specific value, let's stick to "example" for this case, I would like to delete the following two rows after the row(s) which matched the criteria.如果在 B 列中一个单元格包含特定值,让我们坚持“示例”,我想删除符合条件的行之后的以下两行。
It is important to note that the criteria might appear several times within the table and that the table might have different lengths.请务必注意,条件可能会在表格中出现多次,并且表格的长度可能不同。
My idea was the following:我的想法如下:
1. Identify all rows which contain "example" in column B
2. Store the row numbers in a variable
3. Go through the variable and create a new one which has twice the length of the first one and write the two following rows into the 2nd variable
4. Use the 2nd variable to delete the rows with that numbers.
Unfortunately, I am totally new to VBA and was not able to code it.不幸的是,我对 VBA 完全陌生,无法对其进行编码。 I also tried to copy code together but I couldn't find a solution for my specific topic.
我也尝试将代码复制到一起,但找不到适合我的特定主题的解决方案。
This is a very slight mod to your approach这是对您的方法的一个非常轻微的修改
So if row#7 contains "example" , delete row#7 and row#8因此,如果 row#7 包含"example" ,则删除 row#7 和 row#8
Before:前:
The code:编码:
Sub RowKiller()
Dim N As Long, i As Long, t As String
t = "example"
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = N To 1 Step -1
If Cells(i, "B") = t Then
Range(Cells(i + 1, "B"), Cells(i + 2, "B")).EntireRow.Delete
End If
Next i
End Sub
and after:之后:
I think, instead, the best way to handle this is:我认为,相反,处理此问题的最佳方法是:
Thats it.就是这样。
Sub deleteRows()子删除行()
Dim lastRow as Long 'get the last row lastRow = Sheet1.Range("B" & Sheet1.Rows.Count).End(xlUp).Row 'Now work backwards Dim i As Long For i = lastRow to 1 Step -1 'change that 1 to whatever your first row is If Sheet1.Cells(i, 2).value = "Example" Then Sheet1.Rows(i + 1 & ":" & i + 2).Delete End If Next i
End Sub结束子
I haven't tested that, but it looks right.我还没有测试过,但看起来是正确的。 You may have to tweak some things in there, but it will definitely get you in the ballpark.
你可能需要在那里调整一些东西,但它肯定会让你进入球场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.