简体   繁体   English

删除范围内除最后一行以外的空白行

[英]Delete blank rows on range except last row

I have this code where i can search for the first two blank cells and place an "x" on the first cell that contains the blank.我有这段代码,我可以在其中搜索前两个空白单元格,并在第一个包含空白的单元格上放置一个“x”。 For testing purposes i have separated the the code into two command buttons.出于测试目的,我将代码分成两个命令按钮。 For First command button searches the blank cells and places the "x" and second command button finds the "x" and deletes the row and all other rows after it.对于第一个命令按钮搜索空白单元格并放置“x”,第二个命令按钮找到“x”并删除该行和它后面的所有其他行。

My problem is, i want it to delete all rows after the "x" but to leave the last row which contains the overall Total.我的问题是,我希望它删除“x”之后的所有行,但保留包含总计的最后一行。

Here is my code from the two command buttons:这是我的两个命令按钮的代码:

Sub findEmptyCells()

Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 12).End(xlUp).Row 

For i = 12 To lastRow
If Cells(i, 12).Value = "" And Cells(i + 1, 12).Value = "" Then
    Set firstEmptyCell = Cells(i, 12)
    Exit For
End If
Next i

MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"
End Sub



Sub Deleterows_Click()

Dim srchRng As Range

Set srchRng = Range("L7:L500")

Dim c As Range
For Each c In srchRng
If c.Value = "x" Then
    
Range(c, Range("L500")).EntireRow.Delete
              
    Exit For
End If
Next

End Sub

在此处输入图像描述

Delete Rows Identified By Merged Cells删除由合并单元格标识的行

Option Explicit

Sub DeleteRows()
    
    Const Col As String = "L"
    Const fRow As Long = 13
    Const mcCount As Long = 5
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, Col).End(xlUp).Row
    
    Dim cCell As Range
    Dim r As Long

    For r = fRow To lRow - mcCount
        'Debug.Print r
        Set cCell = ws.Cells(r, Col)
        If cCell.MergeArea.Cells.Count = mcCount Then
            If Len(CStr(cCell.Value)) = 0 Then
                cCell.Offset(-1).Resize(lRow - r + 1).EntireRow.Delete
                Exit For
            End If
            r = r + mcCount - 1
        End If
    Next r
    
    MsgBox "Rows deleted.", vbInformation

End Sub

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

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