1

I have an excel file in which I would like delete columns that aren't useful.

Say I have 4 columns: 'ID', 'Name', 'Surname', 'Job'. What I'm trying to do is delete all columns that aren't 'ID' and 'Job'.

I tried using the Range.Find method, but there's obviously something I'm getting wrong.

Any help appreciated

myArray = Array("ID", "Job")
'Delete columns which title aren't in myArray
For j = mycol To 1 Step -1 'col by col
    For k = 0 To 4 'for each element in myArray
        ' Delete col where no elements of myArray are present.
        Columns(j).Delete
    Next k
Next j

EDIT: By columns names, I mean the first row of each column. So A1=ID, B1=Name etc.

7
  • what do you mean by column name? is it just a header in cell in certain row or you are using Tables (ListObjects)? Commented Nov 14, 2016 at 13:03
  • @KazimierzJawor By columns names, I mean the first row of each column. So A1=ID, B1=Name etc. Commented Nov 14, 2016 at 13:11
  • @Daniel Mc check the code in my answer below, let me know if it that's what you meant in your post Commented Nov 14, 2016 at 13:16
  • @ShaiRado That's exactly what I meant. I can't believe I didn't find something so obvious. Thanks Commented Nov 14, 2016 at 13:21
  • @DanielMc you're welcome Commented Nov 14, 2016 at 13:28

2 Answers 2

1

Or you could try with something easier:

For j = myCol To 1 Step -1 'col by col
    'check if column name is in array
    If IsError(Application.Match(Cells(1, j), myArray, 0)) Then
        Columns(j).Delete
    End If

Next j
Sign up to request clarification or add additional context in comments.

2 Comments

That's a very nice method, didn't know it existed!
@KazimierzJawor it is a nice and cleaner answer
0

The code below will loop through all columns (according to your mycol value), and checks if the header in the first row matches any of the elements inside myArray array.

Sub DeleteColumns_NotinArray()

Dim myArray
Dim j As Long, k As Long, mycol As Long
Dim ColHeadrFound   As Boolean

myArray = Array("ID", "Job")

' just for my testing
mycol = 10

'Delete columns which title aren't in myArray
For j = mycol To 1 Step -1 'col by col

    ' reset flag
    ColHeadrFound = False
    For k = 0 To UBound(myArray) 'for each element in myArray
        If Cells(1, j).Value = myArray(k) Then
            ColHeadrFound = True
            Exit For
        End If
    Next k
    ' Delete column where no elements of myArray are present
    If ColHeadrFound = False Then
        Columns(j).EntireColumn.Delete
    End If

Next j


End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.