VBA-only delete rows based off cells that is not in another sheet

Registered55

New Member
Joined
Nov 16, 2014
Messages
19
Hello,

Sheet2 column a has strings that i want to be saved from sheet1

Sheet1 if column H does NOT contain string that is in sheet2 column A
then delete row.

So basically sheet2 contains the list of what i want to keep in sheet1, everything else delete.

sheet2 ColA needs to be dynamic as the list wil grow and shrink accordingly to changes i make.

Thanks.

Sheet1 contains around 10k rows.
 
Hello, after doing some testing in the production field, it's been reported that many rows are being deleted that shouldn't...i have confirmed myself, and indeed this is the case.

the column that i want searched for only is column "X" on sheet 1 if this could have something todo with it.... i'm also going to put the contents below of sheet2 "Keep list" perhaps there is a reason why something is going wrong that you clever people can see.

the below is column A sheet2

VBA Code:
rates
A21
AF2
AF3
AF4
DG3
DG4
FLL03
FLMR4A
FLMRB3
FLMRB4
FLMRRA3
FLPRBB
FLPROM
FLRA3
FLRA3S
FLRA4
FLRA4S
FLRB3
FLRB3S
FLRB4
FLRB4S
FLSEP
FMRA3S
FMRA4S
FMRB3S
FMRB4S
GRA3
GRA3S
GRA4
GRA4S
GRB3
GRB3S
GRB4
GRB4S
IRA3
IRA3S
IRA4
IRA4S
IRB3
IRB3S
IRB4
IRB4S
L03
OAF
PK11
PKGRA1
PKGRA4
PROMAH
PROMBB
QAF
RA3
RA3S
RA4
RA4S
RB3
RB3S
RB4
RB4S
SUPERS
VPR
VPRBB
VPRBUK
STAY


the final code i have for this sub routine above is:

VBA Code:
Sub delrows()
  Worksheets("Sheet1").Activate
  Dim d As Object
  Dim a As Variant, b As Variant, itm As Variant
  Dim nc As Long, i As Long, k As Long
  
  Set d = CreateObject("Scripting.Dictionary")
  a = Sheets("Sheet2").Range("A2", Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp)).Value
  For Each itm In a
    d(itm) = 1
  Next itm
  With Sheets("Sheet1")
    a = .Range("X2", .Range("X" & Rows.Count).End(xlUp)).Value 'X is the rates column
    ReDim b(1 To UBound(a), 1 To 1)
    For i = 1 To UBound(a)
      If Not d.exists(a(i, 1)) Then
        k = k + 1
        b(i, 1) = 1
      End If
    Next i
    If k > 0 Then
      Application.ScreenUpdating = False
      nc = .Cells.Find(What:="*", LookIn:=xlFormulas, searchorder:=xlByColumns, searchdirection:=xlPrevious).Column + 1
      With .Range("A2").Resize(UBound(a), nc)
        .Columns(nc).Value = b
        .Sort Key1:=.Columns(nc), Order1:=xlAscending, Header:=xlNo
        .Resize(k).EntireRow.Delete
      End With
      Application.ScreenUpdating = True
    End If
  End With
End Sub
 
Upvote 0

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
i wanted to share also what is in sheet 1:
Rich (BB code):
Book_idGuest_TypGuest_NumGuest_NameGuest_FirstNameVIPL_LabelCD_NumBOOK_NUMarrival_DateDep_DateROOM_NBTotal_AmountOption_DateDeposit_requiredDeposit_PaidConfirm_dateLinkSPGuarantyGROUP_GENERATEDCommentRoom_TypeSegmentNationalityRateBOOK_SUSPECT_STATUS_IDBOOK_SUSPECT_STATUS
201220​
Individual
135890​
testtest
8214​
JFPLEEEG
########​
########​
1​
201.4​
########​
0​
CC
1​
DBLTAUNITED ARABIAN EMIRATESRA1
1​
Undefined
201467​
Individual
136339​
testtest
7849​
JFSLEEEN
########​
########​
1​
60​
########​
0​
CC
1​
<B>R/HOTEL:</B> Non-Smoking (CRS)<br/><B>R/GUEST:</B> ** Genius Booker ** You have a booker that would prefer a quiet room. (based on availability) (CRS)DBLTEFranceFLRA1
1​
Undefined
 
Upvote 0
Hello, after doing some testing in the production field, it's been reported that many rows are being deleted that shouldn't...i have confirmed myself, and indeed this is the case.
I'm not sure what you have provided adds any clarity to the problem.

What you have given us in post #12 does not show column labels but it seems that the "Rate" heading represents column X.
That column Contains "RA1" and "FLRA1".
Neither of those values are shown in your list for Sheet2 in post #11 so my understanding is that both rows should be deleted and that is what the code does. So I'm not seeing what the problem is. :confused:
 
Upvote 0
ok, apologies i wasn't clear.

there are over 10,000 lines in sheet1, i only gave two rows as an example so you can see a visual of the layout of contents i'm dealing with.
these were deleted when using the above VBA.

even though the FLRA4 is in the keep list.

Rich (BB code):
testJFKGGGKD22/03/2020 00:0048CCFINLANDFLRA4
testJFDGGGNV29/03/2020 00:0043.68CCGreat BritainFLRA4
testJFBGGGWK02/04/2020 00:0052.78CCGreat BritainFLRA4
testJFQGGGJS04/04/2020 00:00123CCGreat BritainFLRA4
testJFSGGGXV08/04/2020 00:00110CCGreat BritainFLRA4
testJFKGGGZW12/04/2020 00:0096.46CCGreat BritainFLRA4
testJFLGGGSH23/04/2020 00:00158.9CCGermanyFLRA4
testJFKGGGDT24/04/2020 00:0086.7CCSWEDENFLRA4
testJFQGGGKW08/05/2020 00:00178.4CCGreat BritainFLRA4

do you have any ideas why these could be removed?

again, i do really appreciate your help, mostly this is working fine, only some are being missed.

and yes, the rates code is in column X

i'm going to paste all the code i have in case something else is breaking....see far below but i understand if you don't wish to as it's a lot.





VBA Code:
Sub FOLSPrePaidRatesListdeleteIrrelevantColumns()
    'Call Rename 'rename sheet 1
    Call Removebadlines 'remove all the lines that are blank and corrupted
    Call AskIfRemoveFlexRates 'this calls importfile and delete not needed rows
    Call FOLSPrePaidRates 'remove all the redundent columns that is not needed
    Call DynamicRange 'this is what puts everything inside a table
    Call Sortrange2 'this sorts certain columns as default, mainly the arrivals list
       
End Sub
   
Sub Rename()
    Sheets(1).Name = "Sheet1"
End Sub

Sub Removebadlines()
    LR3 = Range("A" & Rows.Count).End(xlUp).Row

    For i3 = LR3 To 2 Step -1
        If IsNumeric(Range("A" & i3).Value) And _
        Len(Range("A" & i3).Value) > 0 Then
        Else
            Rows(i3).Delete
        End If
    Next i3
End Sub

Sub DeleteBlankRows()
    Dim SourceRange As Range
    Dim EntireRow As Range

    Set SourceRange = Application.Selection

    If Not (SourceRange Is Nothing) Then
        Application.ScreenUpdating = False

        For i = SourceRange.Rows.Count To 1 Step -1
            Set EntireRow = SourceRange.Cells(i, 1).EntireRow
            If Application.WorksheetFunction.CountA(EntireRow) = 0 Then
                EntireRow.Delete
            End If
        Next

        Application.ScreenUpdating = True
    End If
End Sub

Sub FOLSPrePaidRates()
    Dim keepColumn As Boolean
    Dim currentColumn As Integer
    Dim columnHeading As String

    currentColumn = 1
    While currentColumn <= ActiveSheet.UsedRange.Columns.Count
        columnHeading = ActiveSheet.UsedRange.Cells(1, currentColumn).Value

        'CHECK WHETHER TO KEEP THE COLUMN
        keepColumn = False
        If columnHeading = "Guest_Name" Then keepColumn = True
        If columnHeading = "BOOK_NUM" Then keepColumn = True
        If columnHeading = "arrival_Date" Then keepColumn = True
        If columnHeading = "Total_Amount" Then keepColumn = True
        If columnHeading = "Deposit_Paid" Then keepColumn = True
        If columnHeading = "Guaranty" Then keepColumn = True
        If columnHeading = "Rate" Then keepColumn = True
        If columnHeading = "Nationality" Then keepColumn = True


        If keepColumn Then
        'IF YES THEN SKIP TO THE NEXT COLUMN,
            currentColumn = currentColumn + 1
        Else
        'IF NO DELETE THE COLUMN
            ActiveSheet.Columns(currentColumn).Delete
        End If

        'LASTLY AN ESCAPE IN CASE THE SHEET HAS NO COLUMNS LEFT
        If (ActiveSheet.UsedRange.Address = "$A$1") And (ActiveSheet.Range("$A$1").Text = "") Then Exit Sub
    Wend
End Sub

Sub Sortrange2()
    With ActiveSheet.Sort
    With .SortFields
    .Clear
    .Add Key:=Range("C1"), SortOn:=xlSortOnValues, Order:=xlAscending
    End With
    .SetRange Range("A1").CurrentRegion
    .Header = xlYes
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
    End With
    With ActiveSheet.Cells.EntireColumn.AutoFit
    End With
End Sub

Sub FOLSReservationsResawebListdeleteIrrelevantColumns()
    Call Removebadlines
    Call FOLSResaweb
End Sub

Sub DynamicRange()
    Dim tbl As ListObject
    Dim Rng As Range

    Set Rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Rng, , xlYes)
End Sub
Sub AskIfRemoveFlexRates()

Dim answer As Integer
answer = MsgBox("Do you wish to Remove Flexible Rates from this list?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    Call RatesFileLoaded
    Call delrows
    'Call Macro2
    'Call delrows2
  Else
End If

End Sub
Sub RatesFileLoaded()

Dim answer As Integer
answer = MsgBox("Do you need to import the rates file?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    Call ImportRates
    Else: Sheets(1).Name = "Sheet1"
End If

End Sub

Sub ImportRates()
    Sheets(1).Name = "Sheet1"
    Sheets.Add(after:=Sheets("Sheet1")).Name = "Sheet2"
    Dim wkbCrntWorkBook As Workbook
    Dim wkbSourceBook As Workbook
    Dim rngSourceRange As Range
    Dim rngDestination As Range
    Set wkbCrntWorkBook = ActiveWorkbook
    With Application.FileDialog(msoFileDialogOpen)
        .Filters.Clear
        .Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa"
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count > 0 Then
            Workbooks.Open .SelectedItems(1)
            Set wkbSourceBook = ActiveWorkbook
            Set rngSourceRange = Application.InputBox(prompt:="Select source range", Title:="Source Range", Default:="A1", Type:=8)
            wkbCrntWorkBook.Activate
            Set rngDestination = Application.InputBox(prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8)
            rngSourceRange.Copy rngDestination
            rngDestination.CurrentRegion.EntireColumn.AutoFit
            wkbSourceBook.Close False
        End If
    End With
End Sub


Sub delrows()
  Worksheets("Sheet1").Activate
  Dim d As Object
  Dim a As Variant, b As Variant, itm As Variant
  Dim nc As Long, i As Long, k As Long
 
  Set d = CreateObject("Scripting.Dictionary")
  a = Sheets("Sheet2").Range("A2", Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp)).Value
  For Each itm In a
    d(itm) = 1
  Next itm
  With Sheets("Sheet1")
    a = .Range("X2", .Range("X" & Rows.Count).End(xlUp)).Value 'X is the rates column
    ReDim b(1 To UBound(a), 1 To 1)
    For i = 1 To UBound(a)
      If Not d.exists(a(i, 1)) Then
        k = k + 1
        b(i, 1) = 1
      End If
    Next i
    If k > 0 Then
      Application.ScreenUpdating = False
      nc = .Cells.Find(What:="*", LookIn:=xlFormulas, searchorder:=xlByColumns, searchdirection:=xlPrevious).Column + 1
      With .Range("A2").Resize(UBound(a), nc)
        .Columns(nc).Value = b
        .Sort Key1:=.Columns(nc), Order1:=xlAscending, Header:=xlNo
        .Resize(k).EntireRow.Delete
      End With
      Application.ScreenUpdating = True
    End If
  End With
End Sub

Sub Macro2()

    Const lngStartRow As Long = 2 'Starting (static) row number for the row deletion. Change to suit if necessary.
   
    Dim lngMyCol As Long, _
        lngMyRow As Long
    Dim xlnCalcMethod As XlCalculation
           
    With Application
        xlnCalcMethod = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
    End With
   
    Sheets("Sheet1").Select

    lngMyCol = Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious).Column + 1
    lngMyRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
   
    With Columns(lngMyCol)
        With Range(Cells(lngStartRow, lngMyCol), Cells(lngMyRow, lngMyCol))
            .Formula = "=IF(ISERROR(VLOOKUP(X" & lngStartRow & ",Sheet2!A:A,1,FALSE)),"""",NA())"
            ActiveSheet.Calculate
            .Value = .Value
        End With
        On Error Resume Next 'Turn error reporting off - OK to ignore 'No cells found' message
            .SpecialCells(xlCellTypeConstants, xlErrors).EntireRow.Delete
        On Error GoTo 0 'Turn error reporting back on
        .Delete
    End With
   
    With Application
        .Calculation = xlnCalcMethod
        .ScreenUpdating = True
    End With

    MsgBox "All rows from Col. E where the number is Col. A of Sheet2 have now been deleted.", vbInformation

End Sub

Sub delrows2()
Dim d As Object, e, rws&, cls&, i&, j&
Set d = CreateObject("scripting.dictionary")
For Each e In Sheets("sheet2").Range("A1").CurrentRegion
    d(e.Value) = 1
Next e
Sheets("sheet1").Activate
rws = Cells.Find("*", after:=[a1], searchorder:=xlByRows, _
        searchdirection:=xlPrevious).Row
cls = Cells.Find("*", after:=[a1], searchorder:=xlByColumns, _
        searchdirection:=xlPrevious).Column
For i = rws To 1 Step -1
    For j = 1 To cls
        If d(Range("A1").Resize(rws, cls)(i, j).Value) = 1 Then _
            Cells.Rows(i).Delete: Exit For
Next j, i
End Sub


Sub FOLSResaweb()
    Dim keepColumn As Boolean
    Dim currentColumn As Integer
    Dim columnHeading As String

    currentColumn = 1
    While currentColumn <= ActiveSheet.UsedRange.Columns.Count
        columnHeading = ActiveSheet.UsedRange.Cells(1, currentColumn).Value

        'CHECK WHETHER TO KEEP THE COLUMN
        keepColumn = False
        If columnHeading = "Guest_Name" Then keepColumn = True
        If columnHeading = "Guest_FirstName" Then keepColumn = True
        If columnHeading = "BOOK_NUM" Then keepColumn = True
        If columnHeading = "Dep_Date" Then keepColumn = True
        If columnHeading = "Total_Amount" Then keepColumn = True
        If columnHeading = "Room_Type" Then keepColumn = True
       

        If keepColumn Then
        'IF YES THEN SKIP TO THE NEXT COLUMN,
            currentColumn = currentColumn + 1
        Else
        'IF NO DELETE THE COLUMN
            ActiveSheet.Columns(currentColumn).Delete
        End If

        'LASTLY AN ESCAPE IN CASE THE SHEET HAS NO COLUMNS LEFT
        If (ActiveSheet.UsedRange.Address = "$A$1") And (ActiveSheet.Range("$A$1").Text = "") Then Exit Sub
    Wend
    ActiveSheet.Sort.SortFields.Clear
    ActiveSheet.Sort.SortFields.Add Range("C1"), xlSortOnValues, xlAscending

    With ActiveSheet.Sort
    .SetRange Range("A1").CurrentRegion
    .Header = xlYes
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
    End With

    With ActiveSheet.Cells.EntireColumn.AutoFit
    End With
End Sub
 
Upvote 0
I haven't looked right through that long code, but the data at the top of the post is not deleted by the code in post #11 for me.

Perhaps there are some special non-printing characters in the cell that you cannot see.
Can you provide the sample data again using XL2BB instead of just posting it in code tags?
Or upload a small sample file to a file-share site and provide a link so we can get some actual data to test.
 
Upvote 0
Ok, i can do this...i never used this before, do i need to worry about data protection on this file...or will this XL2BB take care of this?
 
Upvote 0
It should be no different to you providing sample data like you have already. You only need to give us the sample data from column X. For example:

Registered55 Delete Rows2.xlsm
X
1Rate
2FLRA4
3FLRA4
4IRB3
5IRB3S
6FLRB4
7FLRB4S
8FLSEP
9FLRA4
10FLRA4
Sheet1
 
Upvote 0
I think i have found the issue, thanks for asking me to clarify...by doing so it caused be to look into other sections of the code....

certain Rows was deleted to fix corrupted lines that are in the CSV file, however when this happens...the cell location in column X no longer contain the rate code, but something different.

Rich (BB code):
196865​
Individual
133338​
testtest
5409​
JCJLBRLP
########​
########​
1​
325​
325​
########​
0​
Deposit
1​
<B>R/HOTEL:</B> Non-Smoking (CRS)<br/><B>R/FORCG:</B> OTA Desync-CC expiration date (CRS) <span style=font-family: wingdings font-size: 300%">&#252</span><br/><B>R/GUEST:</B> Reservation has a cancellation grace period. Do not charge if cancelled before 2020-01-26 11:42:32
Approximate time of arrival: between 15:00 and 16:00 (CRS)"DBLTHSWEDENFLRA4S
1​
Undefined

the CSV file is imported wrongly on this line because the comments section contains characters that cause the import to go wrong.

i used

VBA Code:
Sub Removebadlines()
    LR3 = Range("A" & Rows.Count).End(xlUp).Row

    For i3 = LR3 To 2 Step -1
        If IsNumeric(Range("A" & i3).Value) And _
        Len(Range("A" & i3).Value) > 0 Then
        Else
            Rows(i3).Delete
        End If
    Next i3
End Sub

to fix this issue, i deleted any line that does not start with a number...but by doing so, i'm deleting something very important...the rate code!!!


Question:

how would i search all rows and columns for the "Rates" instead of just searching column "X": is this possible, or would you advise such a thing?

or is there anything else you can suggest that i haven't though off?



i did try MANY weeks to get excel to import correctly...but the comments sections is what causes issue, never figured out how to get excel to import this CSV file correctly which lead me to find alternatives.

Rich (BB code):
<B>R/HOTEL:</B> Non-Smoking (CRS)<br/><B>R/FORCG:</B> OTA Desync-CC expiration date (CRS) <span style=font-family: wingdings font-size: 300%">&#252</span><br/><B>R/GUEST:</B> Reservation has a cancellation grace period. Do not charge if cancelled before 2020-01-26 11:42:32

this section is what breaks the lines when importing.
 
Last edited:
Upvote 0
Hello, sorry for the edits.....another idea is, how can adjust your macro to also include any blank cell that is in column X

so i want to remove all rows UNLESS the list contains the Cell

but also, Keep the rows if that cell has a blank CELL?

is this possible?

many thanks,
 
Upvote 0
There has been so many changes of layout, requirements and code that I have lost track.

Can you provide some new sample data (with XL2BB) and the expected results & explain the complete requirement again in relation to that sample data?
 
Upvote 0

Forum statistics

Threads
1,223,753
Messages
6,174,307
Members
452,554
Latest member
Louis1225

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top