Excel:VBA删除行组

时间:2017-08-25 19:19:30

标签: excel vba excel-vba

我有一个包含数据列的excel文件。类似的东西:

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

重复几千次。我正在寻找的是所有行,包括21/07/2017和Field 7之间的所有行都要删除,以及要移动的行。

我尝试了一些东西,但现在又回到了空白的画布!任何提示?

由于

我试过的代码

我收到溢出错误

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

1 个答案:

答案 0 :(得分:3)

这只会在对存在的情况下循环次数并删除整个块。

第一次循环结束时,在剩余的值中找不到两者。

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

如果您的日期是真实日期,请将str1更改为Double:

Dim str1 As Double

然后将其指定为:

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