I'm trying to delete any rows in the range "Y3:Y50" where in column "Y", the value is "0".
Dim aRange As Range, aRow As Range, aCell As Range
Set aRange = Range("Y3:Y50")
For Each aRow In aRange.Rows
For Each aCell In aRow.Cells
If aCell.Value = "0" Then
aRow.EntireRow.Delete
Exit For
End If
Next aCell
Next aRow
It is deleting some but not all the rows it should.
The alternative is to delete rows where there is no data in column "A". I feel that would probably be a cleaner option in case I have a row where 0 is the correct value in the future.
Full macro below.
Sub SubbyRunsheet()
Dim rng As Range, URng As Range, cel As Range
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("Runsheet")
Application.ScreenUpdating = False
'Clean up SOR sheet
Sheets("SOR").Activate
With ActiveSheet
.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, "<>" & Worksheets("Runsheet").Range("E1")
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
'Clean up the runsheet
Sheets("Runsheet").Activate
ActiveSheet.Range("A:A").Delete
ActiveSheet.Cells.Select
Cells.WrapText = False
Selection.EntireColumn.AutoFit
'VBasic's code
Const Addr As String = "Y3:Y50"
Const Criteria As Variant = 0
Set rng = ws.Range(Addr)
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
Cells(1, 1).Select
Cells.WrapText = True
ActiveSheet.Range("A2:Y100").RowHeight = 15
Application.DisplayAlerts = False
Worksheets("Reference").Delete
Worksheets("Format Helper").Delete
Worksheets("Airtable Upload").Delete
Worksheets("Formula Sheet").Delete
Application.DisplayAlerts = True
WeekEnding = Format(ActiveSheet.Range("B3").Value, "yyyymmdd")
ActiveWorkbook.SaveAs Filename:="C&I Subcontractor Weekly Runsheet - " & Worksheets("Runsheet").Range("D1") & " WE " & WeekEnding
Application.ScreenUpdating = True
End Sub
Delete Rows With Criteria
Option Explicit
Sub deleteRowsY()
' Constants
Const Addr As String = "Y3:Y50"
Const Criteria As Variant = 0
' If this is happening in the workbook containing this code,
' then use 'Set wb = ThisWorkbook' instead.
Dim wb As Workbook: Set wb = ActiveWorkbook
' The worksheet is better defined by its name,
' e.g. Set ws = wb.Worksheets("Sheet1")
Dim ws As Worksheet: Set ws = wb.ActiveSheet
' Define Column Range.
Dim rng As Range: Set rng = ws.Range(Addr)
' Loop through each cell in Column Range.
Dim cel As Range, URng As Range
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
' Test with hiding, you cannot undo the deletion.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When ready, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
End Sub
Sub deleteRowsA()
' Constants
Const FirstRow As Long = 3
Const tgtCol As Variant = "A" ' e.g. 1 or "A"
Const Criteria As Variant = Empty
' If this is happening in the workbook containing this code,
' then use 'Set wb = ThisWorkbook' instead.
Dim wb As Workbook: Set wb = ActiveWorkbook
' The worksheet is better defined by its name,
' e.g. Set ws = wb.Worksheets("Sheet1")
Dim ws As Worksheet: Set ws = wb.ActiveSheet
' Define Column Range.
Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, tgtCol).End(xlUp).Row
Dim rng As Range
Set rng = ws.Range(ws.Cells(FirstRow, tgtCol), ws.Cells(LastRow, tgtCol))
' Loop through each cell in Column Range.
Dim cel As Range, URng As Range
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
' Test with hiding, you cannot undo the deletion.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When ready, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
End Sub
EDIT:
Option Explicit
Sub deleteY(Sheet As Worksheet, RangeAddress As String, Criteria As Variant)
' Define Column Range.
Dim rng As Range: Set rng = Sheet.Range(RangeAddress)
' Loop through each cell in Column Range.
Dim cel As Range, URng As Range
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
' Test with hiding, you cannot undo the deletion.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When ready, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
End Sub
Sub delY()
' Constants
Const ColumnAddress As String = "Y3:Y50"
Const Criteria As Variant = 0
' Define worksheet.
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
deleteY ws, ColumnAddress, Criteria
End Sub
Sub deleteA(Sheet As Worksheet, _
FirstRow As Long, _
ColumnID As Variant, _
Criteria As Variant)
' Define Column Range.
Dim LastRow As Long
LastRow = Sheet.Cells(Sheet.Rows.Count, ColumnID).End(xlUp).Row
Dim rng As Range
Set rng = ws.Range(ws.Cells(FirstRow, ColumnID), _
ws.Cells(LastRow, ColumnID))
' Loop through each cell in Column Range.
Dim cel As Range, URng As Range
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
' Test with hiding, you cannot undo the deletion.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When ready, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
End Sub
Sub delA()
' Constants
Const FirstRow As Long = 3
Const ColumnID As Variant = "A" ' e.g. 1 or "A"
Const Criteria As Variant = Empty
' Define worksheet.
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
deleteA ws, FirstRow, ColumnID, Criteria
End Sub
Your Final Solution
Option Explicit
Sub SubbyRunsheet()
Const RangeAddress As String = "Y3:Y50"
Const Criteria As Variant = 0
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("Runsheet")
Application.ScreenUpdating = False
'Clean up SOR
Sheets("SOR").Activate
With ActiveSheet
.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, "<>" & Worksheets("Runsheet").Range("E1")
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
'Clean up Runsheet
ws.Activate
ActiveSheet.Range("A:A").Delete
ActiveSheet.Cells.Select
Cells.WrapText = False
Selection.EntireColumn.AutoFit
' Delete rows containing 0-s in Y-column of Runsheet
deleteY ws, RangeAddress, Criteria
Cells(1, 1).Select
Cells.WrapText = True
ActiveSheet.Range("A2:Y100").RowHeight = 15
Application.DisplayAlerts = False
Worksheets("Reference").Delete
Worksheets("Format Helper").Delete
Worksheets("Airtable Upload").Delete
Worksheets("Formula Sheet").Delete
Application.DisplayAlerts = True
WeekEnding = Format(ActiveSheet.Range("B3").Value, "yyyymmdd")
ActiveWorkbook.SaveAs Filename:="C&I Subcontractor Weekly Runsheet - " _
& ws.Range("D1") & " WE " & WeekEnding
Application.ScreenUpdating = True
End Sub
Sub deleteY(Sheet As Worksheet, RangeAddress As String, Criteria As Variant)
' Define Column Range.
Dim rng As Range: Set rng = Sheet.Range(RangeAddress)
' Loop through each cell in Column Range.
Dim cel As Range, URng As Range
For Each cel In rng.Cells
If cel.Value = Criteria Then GoSub collectCells
Next cel
' Test with hiding, you cannot undo the deletion.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When ready, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cel)
Else
Set URng = cel
End If
Return
End Sub
Related
I want to delete all rows in filtered range except the first visible row after header.
For example,
This is a sample table:
I want to delete all the filtered rows of apple Except row number 3 which is the first visible filtered row.
I have tried below code :
Sub Filter()
Dim cl, rng As Range
Range("A1").AutoFilter Field:=1, Criteria1:="Apple"
Set rng = Range("A2:A7")
For Each cl In rng.SpecialCells(xlCellTypeVisible)
cl.EntireRow.Delete
Next cl
End Sub
The problem with this code is that it deletes all the filtered rows. How to specify not to delete first visible row
Use a flag to omit first row
Sub Filter()
Dim cl as Range, rng As Range ' type all variables, otherwise they'll be Variants
Dim FirstRow as Boolean
FirstRow = True
Range("A1").AutoFilter Field:=1, Criteria1:="Apple"
Set rng = Range("A2:A7")
For Each cl In rng.SpecialCells(xlCellTypeVisible)
If Not FirstRow Then
cl.EntireRow.Delete
End If
FirstRow = False
Next cl
End Sub
No need for a loop.
Here is an example
Option Explicit
Sub Filter()
Dim ws As Worksheet
Dim rng As Range
Dim rngFiltered As Range
'~~> Change this to the relevant worksheet
Set ws = Sheet1
With ws
'~~> Remove existing filter
.AutoFilterMode = False
Set rng = ws.Range("A1:A7")
With rng
.AutoFilter Field:=1, Criteria1:="Grapes"
'~~> Check if the 2nd row is hidden
If ws.Rows(.Offset(1, 0).Row).EntireRow.Hidden = True Then
If .SpecialCells(xlCellTypeVisible).Areas.Count > 1 Then _
.Offset(.SpecialCells(xlCellTypeVisible).Areas(2).Row + 1, 0).EntireRow.Delete
Else
.Offset(2, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End If
End With
'.AutoFilterMode = False
End With
End Sub
Delete Filtered Rows But Skip First
Sub DeleteFilteredSkipFirst()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
If ws.AutoFilterMode Then ws.AutoFilterMode = False
Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion ' has headers
Dim drg As Range: Set drg = rg.Resize(rg.Rows.Count - 1).Offset(1) ' no hdrs.
rg.AutoFilter Field:=1, Criteria1:="Apple"
Dim vrg As Range
On Error Resume Next
Set vrg = drg.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
ws.AutoFilterMode = False
If vrg Is Nothing Then Exit Sub
Dim urg As Range, rrg As Range, IsFirstFound As Boolean
For Each rrg In vrg.Rows
If IsFirstFound Then
If urg Is Nothing Then
Set urg = rrg
Else
Set urg = Union(urg, rrg)
End If
Else
IsFirstFound = True
End If
Next rrg
If urg Is Nothing Then Exit Sub
urg.Delete xlShiftUp
MsgBox "Rows deleted.", vbInformation
End Sub
I have code to paste a value into all worksheets in a workbook (it does work but its a little slow).
Then it should when a value is deleted, delete that row from every other worksheet, but it does nothing.
Debugging it looks like the Application.CountBlank(irg) = 1 is never met even though IRG upon cell deletion as the target cell should definitely be blank and a delete should run the worksheet change event.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const cCol As String = "A"
Const fRow As Long = 2
Dim crg As Range
Dim ddFound As Range
Dim ws As Worksheet
Dim sh As Worksheet
Dim outpt As String
Dim i As Integer
Application.EnableEvents = False
Set crg = Columns(cCol).Resize(Rows.Count - fRow + 1).Offset(fRow - 1)
Dim irg As Range: Set irg = Intersect(crg, Target)
Dim sraddress As String
Dim dws As Worksheet
Dim ddcrg As Range
For Each ws In ActiveWorkbook.Worksheets
Set ddcrg = ws.Columns(cCol)
sraddress = irg.Value2
Set ddFound = ddcrg.Find(sraddress, , xlValues, xlWhole)
Application.ScreenUpdating = False
If Application.CountBlank(irg) = 0 Then
If ddFound Is Nothing Then
irg.Select: ActiveCell = irg.Value2
irg.Copy
ws.Range(irg.Address) = irg.Value2
Application.CutCopyMode = False
ElseIf Application.CountBlank(irg) = 1 And ddFound Is Nothing Then
Sheets(Array("Statistics", "January")).Select
ddFound.EntireRow.Delete Shift:=xlShiftUp
End If
End If
Next ws
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Please, try the next code. It assumes that Target may have more columns, but only one row:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const cCol As String = "A"
Const fRow As Long = 2
Dim crg As Range, ddFound As Range, ws As Worksheet, i As Long
Application.EnableEvents = False
Set crg = Columns(cCol).Resize(rows.Count - fRow + 1).Offset(fRow - 1)
Dim irg As Range: Set irg = Intersect(crg, Target)
If Target.rows.Count > 1 Then Exit Sub 'no more then one row admitted
If irg Is Nothing Then Exit Sub
Dim sraddress As String, ddcrg As Range
Dim rngDelS As Range, rngDelJ As Range 'ranges to keep rows to be deleted
For Each ws In ActiveWorkbook.Worksheets
If ws.Index <= 13 Then
Set ddcrg = ws.Columns(cCol)
sraddress = irg.Value2
Set ddFound = ddcrg.Find(sraddress, , xlValues, xlWhole)
If irg.Value <> "" Then
If ddFound Is Nothing Then
ws.Range(irg.Address).Value2 = irg.Value2
End If
ElseIf irg.Value = "" And Not ddFound Is Nothing Then
If rngDelS Is Nothing Then
Set rngDelS = Sheets("Statistics").Range(ddFound.Address)
Set rngDelJ = Sheets("January").Range(ddFound.Address)
Else
Set rngDelS = Union(rngDelS, Sheets("Statistics").Range(ddFound.Address))
Set rngDelJ = Union(rngDelJ, Sheets("January").Range(ddFound.Address))
End If
End If
End If
Next ws
If Not rngDelS Is Nothing Then 'delete the necessary rows, at once, per each sheet:
rngDelS.EntireRow.Delete
rngDelJ.EntireRow.Delete
End If
Application.EnableEvents = True
End Sub
I have two worksheets
Source(ThisWorkbook) - contains multiple worksheets
Destination(WBD) - contains 1 worksheet
This is the process:
Compare each cell from a range in WBD (B2:B6) to all worksheet names in ThisWorkbook
If a match is found, from a range in WBD (C2:C7) and look for it in the matched worksheet
(this is where I'm having troubles)How do I get the value of the avg price cell? Do I need another loop?
*the distance between type and price is consistent.
Here's what I got so far:
For Each cel In WBD.Worksheets(1).Range("B2:B6")
For Each ws In ThisWorkbook.Worksheets
ws.Activate
If ws.Name = cel.Value Then
'find C2:C7 , offset, copy avg price, paste
Next ws
Next cel
Source - ThisWorkbook
Destination - WBD
A Lookup by Worksheets
An Application.Match Approach
Option Explicit
Sub lookupValues()
Const dFirst As Long = 2
Const sFirst As Long = 2
Dim swb As Workbook: Set swb = ThisWorkbook
'Dim WBD As Workbook: Set WBD = ThisWorkbook
Dim drg As Range
Dim dLast As Long
With WBD.Worksheets(1)
dLast = .Cells(.Rows.Count, "C").End(xlUp).Row ' because merged in 'B'
Set drg = .Cells(dFirst, "B").Resize(dLast - dFirst + 1)
End With
Dim src As Worksheet
Dim srg As Range
Dim cel As Range
Dim dMatch As Variant
Dim sMatch As Variant
Dim sLast As Long
For Each src In swb.Worksheets
sLast = src.Cells(src.Rows.Count, "C").End(xlUp).Row
Set srg = Nothing
On Error Resume Next
Set srg = src.Cells(sFirst, "B").Resize(sLast - sFirst + 1)
On Error GoTo 0
If Not srg Is Nothing Then
dMatch = Application.Match(src.Name, drg, 0)
If IsNumeric(dMatch) Then
Set cel = drg.Cells(dMatch)
Do
sMatch = Application.Match(cel.Offset(, 1).Value, srg, 0)
If IsNumeric(sMatch) Then
cel.Offset(, 2).Value _
= srg.Cells(sMatch).Offset(3, 2).Value
End If
Set cel = cel.Offset(, 1).Offset(1, -1) ' because merged
Loop Until Len(cel.Value) > 0 Or cel.Row > dLast
End If
End If
Next src
'WBD.Save
'swb.Close SaveChanges:=False
End Sub
Sub m1()
For Each cel In ThisWorkbook.Worksheets(1).Range("B2:B6")
If cel.MergeCells Then
shname = cel.MergeArea.Cells(1, 1).Value ' if cells merged, only first cell contains value
Else
shname = cel.Value
End If
For Each ws In ThisWorkbook.Worksheets
If ws.Name = shname Then
Set f = ws.Columns("B").Find(cel.Offset(0, 1).Value, lookat:=xlWhole)
If Not f Is Nothing Then ' its found
Set f = ws.Cells.Find("avg price", after:=f.Offset(0, 1))
If Not f Is Nothing Then ' its found
cel.Offset(0, 2).Value = f.Offset(0, 1).Value
End If
End If
End If
Next ws
Next cel
End Sub
I have a macro that runs an anti-filter concept and pastes the results into a sheet called "AF".
How can I adjust this so instead of pasting Column T from "CurrentList" it pastes columns A:Q. I tried tweaking some of the variables.
Option Explicit
Sub XC()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim src As Worksheet
Set src = wb.Worksheets("CurrentList")
Dim LastRow As Long
LastRow = src.Cells(src.Rows.Count, "S").End(xlUp).Row
Dim rng As Range
Set rng = src.Range("S1").Resize(LastRow)
Dim Lookup As Variant
Lookup = rng.Value
Set rng = src.Range("T1").Resize(LastRow)
Dim Result As Variant
Result = rng.Value
Dim LookupValue As Variant
Dim i As Long
Dim MatchCount As Long
For i = 1 To UBound(Lookup)
LookupValue = Lookup(i, 1)
If Not IsError(LookupValue) Then
If LookupValue = "Yes" Then
MatchCount = MatchCount + 1
Result(MatchCount, 1) = Result(i, 1)
End If
End If
Next i
If MatchCount = 0 Then
Exit Sub
End If
Dim dst As Worksheet
Set dst = wb.Worksheets("AF")
Set rng = dst.Cells(dst.Rows.Count, "A").End(xlUp).Offset(1)
Set rng = rng.Resize(MatchCount)
rng.Value = Result
MsgBox "Data transferred.", vbInformation, "Success"
End Sub
Give this a try. You'll have to adjust sheet names.
Sub x()
Dim rData As Range
Application.ScreenUpdating = False
With Worksheets("CurrentList")
.AutoFilterMode = False
.Range("A1").CurrentRegion.AutoFilter field:=19, Criteria1:="Yes"
With .AutoFilter.Range
On Error Resume Next
Set rData = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not rData Is Nothing Then
Intersect(rData, .Range("A:Q")).Copy Worksheets("AF").Range("A" & Rows.Count).End(xlUp)(2)
End If
End With
.AutoFilterMode = False
End With
Application.ScreenUpdating = True
End Sub
I am new to VBA... I am trying delete all columns from Sheet1:"Template" ROW1/headers file that doesn't match any of the cell values on varList:"ColumnsList" (that is in Sheet3).
How do I select the headers or how do I select the row 1 range to search into?
Also, I have a runtime error 5 in this line: invalid procedure call or argument.
If Intersect(rng.Cells(1, i).EntireColumn, rngF) Is Nothing Then
Any kind soul that help me with that please?
Also, I need to do the same but with rows from Sheet1:"Template". I need to delete any row that doesn't CONTAIN any cell value from varList:"Agents" (that is in Sheet2).
Could you please help me out?
Maaaany thanks in advance!!!
Option Compare Text
Sub ModifyTICBData()
Dim varList As Variant
Dim lngarrCounter As Long
Dim rngFound As Range, rngToDelete As Range
Dim strFirstAddress As String
'Application.ScreenUpdating = False
varList = VBA.Array("ColumnsList") 'I want to keep columns with these values, NOT DELETE THEM
For lngarrCounter = LBound(varList) To UBound(varList)
With Sheets("Template").UsedRange
Set rngFound = .Find( _
What:=varList(lngarrCounter), _
Lookat:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=True)
If Not rngFound Is Nothing Then
strFirstAddress = rngFound.Address
If rngToDelete Is Nothing Then
Set rngToDelete = rngFound
Else
If Application.Intersect(rngToDelete, rngFound.EntireColumn) Is Nothing Then
Set rngToDelete = Application.Union(rngToDelete, rngFound)
End If
End If
Set rngFound = .FindNext(After:=rngFound)
Do Until rngFound.Address = strFirstAddress
If Application.Intersect(rngToDelete, rngFound.EntireColumn) Is Nothing Then
Set rngToDelete = Application.Union(rngToDelete, rngFound)
End If
Set rngFound = .FindNext(After:=rngFound)
Loop
End If
End With
Next lngarrCounter
Dim rngDel As Range
Set rngDel = NotIntersectRng(Sheets("Template").UsedRange, rngToDelete)
If Not rngDel Is Nothing Then rngDel.EntireColumn.delete
'Application.ScreenUpdating = True
End Sub
Private Function NotIntersectRng(rng As Range, rngF As Range) As Range
Dim rngNI As Range, i As Long, j As Long
For i = 1 To rng.Columns.Count
**If Intersect(rng.Cells(1, i).EntireColumn, rngF) Is Nothing Then**
If rngNI Is Nothing Then
Set rngNI = rng.Cells(1, i)
Else
Set rngNI = Union(rngNI, rng.Cells(1, i))
End If
End If
Next i
If Not rngNI Is Nothing Then Set NotIntersectRng = rngNI
End Function
Delete Columns, Then Rows
Description
Deletes columns that in the first row do not contain values from a list. Then deletes rows that in the first column do not contain values from another list.
The Flow
Writes the values from range A2 to the last cell in Sheet3 to the Cols Array.
Writes the values from range A2 to the last cell in Sheet2 to the Agents Array.
Using CurrentRegion defines the DataSet Range (rng).
Loops through the cells (cel) in first row starting from the 2nd column and compares their values to the values from the Cols Array. If not found adds the cells to the Delete Range(rngDel).
Finally deletes the entire columns of the cells 'collected'.
Loops through the cells (cel) in first column starting from the 2nd row and compares their values to the values from the Agents Array. If not found adds the cells to the Delete Range(rngDel).
Finally deletes the entire rows of the cells 'collected'.
Informs the user of success or no action.
The Code
Option Explicit
Sub ModifyTICBData()
' Define workbook ('wb').
Dim wb As Workbook
Set wb = ThisWorkbook
' Define Columns List ('Cols').
Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet3")
Dim rng As Range
Set rng = ws.Cells(ws.Rows.Count, "A").End(xlUp)
Dim Cols As Variant
Cols = ws.Range("A2", rng).Value
' Define Agents List ('Agents').
Set ws = wb.Worksheets("Sheet2")
Set rng = ws.Cells(ws.Rows.Count, "A").End(xlUp)
Dim Agents As Variant
Agents = ws.Range("A2", rng).Value
' Define DataSet Range ('rng').
Set rng = wb.Worksheets("Template").Range("A1").CurrentRegion
Application.ScreenUpdating = False
' Define Delete Range ('rngDel') for Columns.
Dim rngDel As Range
Dim cel As Range
For Each cel In rng.Rows(1).Resize(, rng.Columns.Count - 1) _
.Offset(, 1).Cells
If IsError(Application.Match(cel.Value, Cols, 0)) Then
collectCells rngDel, cel
End If
Next cel
' Delete Columns.
Dim AlreadyDeleted As Boolean
If Not rngDel Is Nothing Then
rngDel.EntireColumn.Delete
Else
AlreadyDeleted = True
End If
' Define Delete Range ('rngDel') for Agents.
Set rngDel = Nothing
For Each cel In rng.Columns("A").Resize(rng.Rows.Count - 1) _
.Offset(1).Cells
If IsError(Application.Match(cel.Value, Agents, 0)) Then
collectCells rngDel, cel
End If
Next cel
' Delete Agents (Rows).
If Not rngDel Is Nothing Then
rngDel.EntireRow.Delete
AlreadyDeleted = False
End If
Application.ScreenUpdating = True
' Inform user
If Not AlreadyDeleted Then
MsgBox "The data was succesfully deleted.", vbInformation, "Success"
Else
MsgBox "The data had already been deleted.", vbExclamation, "No Action"
End If
End Sub
Sub collectCells(ByRef CollectRange As Range, CollectCell As Range)
If Not CollectCell Is Nothing Then
If Not CollectRange Is Nothing Then
Set CollectRange = Union(CollectRange, CollectCell)
Else
Set CollectRange = CollectCell
End If
End If
End Sub