lundi 9 décembre 2019

Excel VBA IF statement based on partial cell value

I have the following code in ThisWorkbook to copy a template sheet whenever a new sheet is added. Once copied, it renames it from TEMPLATE (2) to Sheet1, etc.

Private Sub Workbook_NewSheet(ByVal Sh As Object)

Dim tmpName As String
tmpName = Sh.Name

Sheets("TEMPLATE").Copy Before:=Sheets(Sh.Name)
Application.DisplayAlerts = False
Sheets(Sh.Name).Delete
Application.DisplayAlerts = True
Sheets("TEMPLATE (2)").Name = tmpName

End Sub

There are tables on the sheet that are tied to power queries (the queries pull from our financial data and there will be a sheet for each manager). I have a formula in cell A1 that reflects the name of the sheet. The process will be that when a sheet is added, the new manger's name will be entered as the sheet name. On the template, and therefore each subsequent sheet, I have the following code to filter based on the value in A1:

Private Sub Worksheet_Activate()

Dim pm As String
pm = Range("A1").Value


ActiveSheet.ListObjects(1).Range.AutoFilter Field:=5, Criteria1:= _
    "=" & pm
ActiveSheet.ListObjects(2).Range.AutoFilter Field:=5, Criteria1:= _
    "=" & pm
ActiveSheet.ListObjects(3).Range.AutoFilter Field:=5, Criteria1:= _
    "=" & pm

End Sub

I don't want the filter code to run until the sheet has been renamed. I'm thinking I need some sort of if statement that will run the filter code if A1 does not have contain the text "Sheet" as part of the value, but since it may be Sheet1, Sheet2, etc., I would need it to see if "Sheet" was part of the cell value, not the whole value.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire