Impossible de faire correspondre le nom de la colonne

Je search le nom de la colonne, mais mon code ne fonctionne pas. C'est ce que j'ai essayé:

word = "sample" Set aCell = ActiveSheet.Rows(1).Find(What:=word, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) lastRow = Cells(1, Columns.count).End(xlToLeft).Column For k = 0 To lastRow If aCell Is Nothing Then aCell.Offset(0, 1).EntireColumn.Delete End If Next k 

Tout ce que je veux faire, c'est de supprimer toute la colonne si elle est trouvée. De l'aide ?

Vous pouvez le faire de cette façon:

 Sub deleteColumn() Dim headerColumnToDelete As Ssortingng Dim endRow As Integer Dim counter As Integer endRow = Cells(1, Columns.Count).End(xlToLeft).Column headerColumnToDelete = "sample" For counter = endRow To 1 Step -1 If Cells(1, counter) = headerColumnToDelete Then Cells(1, counter).EntireColumn.Delete End If Next counter End Sub 

Si vous souhaitez supprimer la colonne complète avec l'en-tête de colonne "échantillon", essayez ceci dans un module:

 Public Sub DeleteSample() DeleteColumn ("sample") End Sub Public Sub DeleteColumn(Name As Ssortingng) 'Get the header row Dim row As Range Set row = Rows(1) 'Find the cell containing Name in that row Dim result As Range Set result = row.Find(Name) Dim wholeColumn As Range 'Select the whole column (or quit if it's not found) On Error GoTo Catch Set wholeColumn = result.EntireColumn() On Error GoTo 0 'Delete the whole column and shift cells left wholeColumn.Delete xlShiftToLeft Catch: Exit Sub End Sub 

Vous n'avez pas besoin d'une boucle For, vous pouvez simplement utiliser l'API Excel pour find la cellule 🙂

 Sub columndelete() Dim lastcolumn As Long word = "sample" lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To lastcolumn If Cells(1, i).Value = word Then Cells(1, i).EntireColumn.Delete End If Next i End Sub 

Je viens de faire quelques changements dans votre code:

 Sub test() word = "sample" Set acell = ActiveSheet.Rows(1).Find(What:=word, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not (acell Is Nothing) Then acell.EntireColumn.Delete End If End Sub