简体   繁体   中英

Excel VBA - Search/Select/Delete Range Based on Next Non-Blank Cell in Column

I'm hoping someone will be able to help me out with this.

My intent is to have the worksheet search for a name and find it. I've got that done without issues with the following code:

Sub Removemember_Click()
MemberName = InputBox(Prompt:="Enter Member's Name")
Cells.Find(What:=MemberName, _
After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate
End Sub

What I need to do next is search downward in the "C" column until I find a non-blank cell, then select all rows between the searched-for name and the next name (though not including the next name). Then I need to delete (remove) the rows. Can anyone lend me a hand?

The code below provides one way. Once you understand it, modify as needed and remove the .select statements.

在此处输入图片说明

Option Explicit
Sub Removemember_Click()
Dim memberName As String
Dim startR As Range, endR As Range, rangeToDelete As Range
Set startR = ActiveSheet.Range("C1")
startR.Activate
memberName = InputBox(Prompt:="Enter Member's Name")
Set startR = Cells.Find(What:=memberName, _
After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False)
Set endR = startR.End(xlDown).Offset(-1, 0)
startR.Select
endR.Select
Set rangeToDelete = Rows(startR.Offset(1, 0).Row & ":" & endR.Row)
rangeToDelete.Select
rangeToDelete.Delete
End Sub

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