简体   繁体   中英

Excel: VBA to delete group of rows

I have an excel file with one column with data. Something like:

21/07/2017
DEF
GHI
Field 7
SOMETHING HERE
MORE TEXT
21/07/2017
DEF
GHI
Field 7

This is repeated a few thousand times. What I am looking for is all rows between and including 21/07/2017 and Field 7 to be deleted and for the rows to be moved up.

I've tried a few things but now back to a blank canvas! Any hints?

Thanks

CODE I TRIED

I get an Overflow error

Sub deleteRows()
    Dim sh As Worksheet
    Dim rw As Range
    Dim RowCount As Integer

    RowCount = 1
    Application.DisplayAlerts = False
    Set sh = ActiveSheet
    For Each rw In sh.Rows

      If sh.Cells(rw.Row, 1).Value = "21/07/2017" Then
        a = RowCount
      End If
      If sh.Cells(rw.Row, 1).Value = "Field 7" Then
        b = RowCount
        Rows(a & ":" & b).Delete
      End If

      RowCount = RowCount + 1

    Next rw
End Sub

This will only loop as many times as the pair exists and delete each block as a whole.

The loop ends the first time that both are not found in the remaining values.

Sub myDelete()
Dim str1 As string
Dim str2 As String
Dim rng As Range
Dim ws As Worksheet
Dim i As Long
Dim j As Long

str1 = "21/07/2017"
str2 = "Field 7"

Set ws = Worksheets("Sheet18") 'change to your worksheet
Set rng = ws.Range("A:A")


Do
    i = 0: j = 0
    On Error Resume Next
        i = Application.WorksheetFunction.Match(str1, rng, 0)
        j = Application.WorksheetFunction.Match(str2, rng, 0)
    On Error GoTo 0
    If i > 0 And j > 0 Then
        ws.Rows(i & ":" & j).Delete
    End If
Loop Until i = 0 Or j = 0
End Sub

If your date is a true date then change str1 to Double:

Dim str1 As Double

and then assign it as such:

str1 = CDbl(DateSerial(2017, 7, 21))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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