删除 excel 中的行

Remove rows in excel

这是一个棘手的问题。

我有一个 Excel 文件,工作簿中的 10 个 sheet 中的每一个都包含大约 4000 篇文章。我想只保留大约 400 篇文章,其余 3600 篇文章应该被删除。

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

所有 sheet 的第 1-5 行都有 headers。

文章 ID 可以在某些 sheet 中存在多次。

我想在 Visual Basic 脚本本身中列出 400 篇文章 ID,这样我就不必创建单独的 sheet 或包含信息的列。

有人可以帮助我吗?我尝试了很多脚本,但似乎没有任何效果...

在下面的示例中,我想保留文章 ID 的 5 和 1(当然还有 headers)。应删除剩余的 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. 它只适用于打开的 sheet 而不是整个工作簿。

亲切的问候,

彼得

试试这个代码

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

试试这个代码。一开始它会询问您要在所有工作表中保留哪些 ID。在那里输入以逗号分隔的数字 (,),除逗号和数字外,不允许有空格或字符。

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