I am working on optimizing this script since I am working with two large (~1M rows) worksheets, each and think my code is inefficient and takes way too long to run and wondering if I can redo it to make it faster.
These are the steps:
- Combine Excel Sheet 1 and Sheet 2 using Column
A
as common identifier - Add a column to identify if Columns
E = H
(True
orFalse
) - Remove all
True
's (this should get rid of most rows, leaving a few hundred)
Also, what does this line exactly mean? in particular the Columns (1)
, A
, :M
and G
- want to confirm its picking the right matches
iRow = Application.Match(ID, ws2.UsedRange.Columns(1), 0)
If Not IsError(iRow) Then ws2.Range("A" & iRow & ":M" & iRow).Copy ws3.Range("G" & r.Row)
Sheet 1:
Sheet 2:
Final Expected Result:
Sub TestGridUpdate()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim TestGridFound As Boolean, r As Range
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Set ws2 = ThisWorkbook.Worksheets("Sheet2")
TestGridFound = False 'Look for TestGrid worksheet
For Each ws In Worksheets
If ws.Name = "Combined" Then TestGridFound = True
Next
If TestGridFound Then 'If Combined is found then use it else create it
Set ws3 = ThisWorkbook.Worksheets("Combined")
ws3.Cells.Clear
Else
Set ws3 = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
ws3.Name = "Combined"
End If
ws3.Range(ws1.UsedRange.Address).Value = ws1.UsedRange.Value 'Copy ws1 to ws3 (TestGrid)
For Each r In ws3.UsedRange.Rows ' Add ws2 details to ws3 (TestGrid)
ID = r.Cells(, 1).Value
iRow = Application.Match(ID, ws2.UsedRange.Columns(1), 0)
If Not IsError(iRow) Then ws2.Range("A" & iRow & ":M" & iRow).Copy ws3.Range("G" & r.Row)
Next
End Sub
Sub FillFormula() 'Add a column to identify column matches
'Set reference to the sheet in the workbook.
Set ws = ThisWorkbook.Worksheets("Combined")
ws.Activate 'not required but allows user to view sheet if warning message appears
Range("N2").Formula = "=$E2=H2"
Range("N2", "N" & Cells(Rows.Count, 1).End(xlUp).Row).FillDown
End Sub
Sub Delete_Rows_Based_On_Value() 'Delete all matches that are true'
'Apply a filter to a Range and delete visible rows
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Combined") 'Set reference to sheet in workbook.
ws.Activate 'not required but allows user to view sheet if warning message appears
On Error Resume Next 'Clear any existing filters
ws.ShowAllData
On Error GoTo 0
ws.Range("A:P").AutoFilter Field:=14, Criteria1:="TRUE" '1. Apply Filter
Application.DisplayAlerts = False '2. Delete Rows
Sheets("Combined").AutoFilter.Range.Offset(1).Delete xlShiftUp
Application.DisplayAlerts = True
On Error Resume Next '3. Clear Filter
ws.ShowAllData
On Error GoTo 0
End Sub