简体   繁体   English

删除Excel工作表中的特定行

[英]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这是对您的方法的一个非常轻微的修改

  • starting from the bottom of column B , work upwards.B列的底部开始,向上工作。
  • if we encounter "example" , delete the two rows below如果我们遇到"example" ,请删除下面的两行

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:我认为,相反,处理此问题的最佳方法是:

  1. Loop through all of the populated rows from the last to the first.从最后到第一个循环遍历所有填充的行。 (this insures we don't pull the rug out from under us when deleting rows). (这可确保我们在删除行时不会从下方拉出地毯)。
  2. If "Example" is found in column B of that row, delete the two rows after it (we've already traversed those rows so deleting shouldn't be any big deal如果在该行的 B 列中找到“示例”,则删除它后面的两行(我们已经遍历了这些行,因此删除应该没什么大不了的)
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM