删除excel中的行

这是一个棘手的问题。

我有一个Excel文件,其中包含工作簿中10张工作表中的大约4000篇文章。 我只想保留约400条,剩下的3600条应该删除。

工作簿中的所有工作表都有A列中的文章ID。

所有工作表在第1-5行都有标题。

文章ID在一些表单中可以存在多次。

我想在Visual Basic脚本中列出400个文章ID,这样我就不必创build包含信息的单独的工作表或列。

有人可以帮帮我吗? 我已经尝试了这么多的脚本,但似乎没有工作…

在下面的例子中,我想保留文章ID的5和1(当然还有头文件)。 剩下的5行应该被删除

在这里输入图像说明

在这里输入图像说明

这是我曾经试过的:

Sub Delete() Dim Firstrow As Long Dim Lastrow As Long Dim Lrow As Long Dim CalcMode As Long Dim ViewMode As Long With Application CalcMode = .Calculation .Calculation = xlCalculationManual .ScreenUpdating = False End With With ActiveSheet .Select ViewMode = ActiveWindow.View ActiveWindow.View = xlNormalView .DisplayPageBreaks = False Firstrow = 6 Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row For Lrow = Lastrow To Firstrow Step -1 With .Cells(Lrow, "Y") If Not IsError(.Value) Then If InStr(.Value, 1) = 0 Or InStr(.Value, 5) = 0 Then .EntireRow.Delete End If End With Next Lrow End With End Sub 

但是,我得到两个问题:

  1. 所有的行都被删除, 包括我想删除的行(1和5)。

  2. 它只适用于打开的工作表,而不是整个工作簿。

亲切的问候,

彼得

试试这个代码。 在开始时,它会询问你想保留在所有工作表中的ID。 在那里input以逗号( , )分隔的数字,不允许使用逗号和数字以外的空格或字符。

 Sub DeleteArticles() Dim i As Long Dim strIDToKeep As String Dim arrIDToKeep() As String Dim ws As Worksheet Dim lastRow As Long strIDToKeep = InputBox("What IDs to keep?") arrIDToKeep = Split(strIDToKeep, ",") For Each ws In Worksheets lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row For i = lastRow To 6 Step -1 'if ID isn't present in array of IDs to keep, then we delete entire row If UBound(Filter(arrIDToKeep, ws.Cells(i, 1).Value)) = -1 Then ws.Rows(i).EntireRow.Delete End If Next Next End Sub 

试试这个代码

 Sub Test() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets Dim i As Long For i = 10 To 2 Step -1 Select Case ws.Cells(i, 1).Value 'add your ids for which you don't want to delete the rows Case 1, 5 'do nothing Case Else ws.Cells(i, 1).EntireRow.Delete End Select Next i Next ws End Sub