gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
give the macro code to delete rows in a sheet that doesnt contains the strins in their b…
- User
give the macro code to delete rows in a sheet that doesnt contains the strins in their b column that present in sheet1's a column
- Assistant
Sure! Here's a macro code that will delete rows in Sheet2 if their B column values are not present in Sheet1's A column:
VBASub DeleteRows() Dim ws1 As Worksheet, ws2 As Worksheet Dim rng1 As Range, rng2 As Range, cell As Range Dim lastRow1 As Long, lastRow2 As Long 'Set the worksheets Set ws1 = ThisWorkbook.Sheets("Sheet1") Set ws2 = ThisWorkbook.Sheets("Sheet2") 'Set the ranges to check lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row lastRow2 = ws2.Cells(ws2.Rows.Count, "B").End(xlUp).Row Set rng1 = ws1.Range("A1:A" & lastRow1) Set rng2 = ws2.Range("B1:B" & lastRow2) 'Loop through each cell in Sheet2's B column For Each cell In rng2 'Check if the cell value is not in Sheet1's A column If Application.WorksheetFunction.CountIf(rng1, cell.Value) = 0 Then 'Delete the entire row cell.EntireRow.Delete End If Next cell End Sub