Sub Auto_Open()
Dim cnt, count, lrow, lastrow, cust_col, comp_col, own_col As Long
Dim sheetname, customer, company, owner As String
lrow = Worksheets("Master").Cells(Rows.count, 1).End(xlUp).Row
With Worksheets("Master")
comp_col = Application.Match("Company", .Rows(1), 0)
cust_col = Application.Match("Customer Name", .Rows(1), 0)
own_col = Application.Match("Owner", .Rows(1), 0)
End With
For cnt = 2 To lrow
customer = UCase(Worksheets("Master").Cells(cnt, cust_col).Value)
company = UCase(Worksheets("Master").Cells(cnt, comp_col).Value)
owner = UCase(Worksheets("Master").Cells(cnt, own_col).Value)
sheetname = customer & ", " & company & ", " & owner
If SheetExists(sheetname) Then 'check you have a customer worksheet of that name in the workbook (using private function below)
lastrow = Worksheets(sheetname).Cells(Rows.count, 1).End(xlUp).Row 'get last row of customer sheet
For count = lastrow To 2 Step -1 'now search through the list to delete unwanted items
If UCase(Worksheets(sheetname).Cells(count, cust_col)) <> customer Or UCase(Worksheets(sheetname).Cells(count, comp_col)) <> company Or UCase(Worksheets(sheetname).Cells(count, own_col)) <> owner Then
Worksheets(sheetname).Cells(count, 2).EntireRow.Delete
End If
Next count
Else
MsgBox ("Customer '" & sheetname & "' has no sheet")
End If
Next cnt
End Sub
Private Function SheetExists(Tabname) As Boolean
' Returns TRUE if sheet exists in the active workbook
Dim x As Object
On Error Resume Next
Set x = ActiveWorkbook.Sheets(Tabname)
If Err = 0 Then SheetExists = True _
Else SheetExists = False
End Function