简体   繁体   English

根据ID和单元格值在Excel中删除行

[英]Deleting rows in Excel according to ID and cell value

I have an excel worksheet with a lot of data that needs pruning. 我有一个Excel工作表,其中包含许多需要修剪的数据。

Data is a organized by ID number with multiple rows attached to a given ID. 数据是按ID号组织的,其中多个行附加到给定的ID。 For each unique ID, I need to to keep all rows with certain codes (which are found in column B). 对于每个唯一ID,我需要保留所有带有特定代码的行(可在B列中找到)。 I also need to keep the rows immediately above the rows with the "keeper codes," provided such a row exists. 如果存在这样的行,我还需要将这些行紧靠在行上方并带有“保持者代码”。 If no such row exists, then I need to insert a blank row.* 如果不存在这样的行,那么我需要插入一个空白行。*

For a given ID, if no "keeper code" is present, then all rows associated with the ID should be deleted. 对于给定的ID,如果不存在“管理员代码”,则应删除与该ID关联的所有行。 All rows not associated with a "keeper code" or immediately above a row with a "keeper code" should be deleted. 与“保持者代码”无关的所有行,或与“保持者代码”行紧邻的所有行都应删除。

Probably best explained by screenshot. 最好用截图来解释。 Data will be sorted by ID number as pictured. 如图所示,数据将按ID号排序。

之前

后

*Inserting a blank row would be nice but if it makes the coding difficult then is not very necessary. *插入空白行会很好,但是如果这样会使编码变得困难,则不是必须的。

Thanks much! 非常感谢!

Try this out, 试试看

Sub copyRows()
Dim i As Long, j As Long
Sheets.Add.Name = "newSheet"
Rows(1).Copy Sheets("newSheet").Cells(1, 1)
j = Sheets("newSheet").Cells(Rows.Count, 1).End(xlUp).Row + 1
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    If InStr(Cells(i, 2), "Keep") > 0 And Cells(i, 1) = Cells(i - 1, 1) Then
        Rows(i - 1).Copy Sheets("newSheet").Cells(j, 1)
        Rows(i).Copy Sheets("newSheet").Cells(j + 1, 1)
    ElseIf InStr(Cells(i, 2), "Keep") > 0 Then
        Rows(i).Copy Sheets("newSheet").Cells(j, 1)
    End If
    j = Sheets("newSheet").Cells(Rows.Count, 1).End(xlUp).Row + 1
Next i
End Sub

If inserting empty rows is necessary you may have to work on that logic. 如果需要插入空行,则可能必须处理该逻辑。

在此处输入图片说明

This macro creates a new sheet with the output. 此宏使用输出创建一个新工作表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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