+ Reply to Thread
Results 1 to 2 of 2

Deleting all but a few columns

Hybrid View

  1. #1
    Registered User
    Join Date
    12-15-2010
    Location
    Portland, OR
    MS-Off Ver
    Excel 2007
    Posts
    3

    Deleting all but a few columns

    I'm very new to this, so bare with me. What I'm trying to do is create a function that will delete all but a few specific named columns. We're getting data from a lab with a ton of columns in every sheet that we don't need, and I want to be able to quickly delete the superfluous info. I tried to convert another function I found, but can't get it to do what I want. As you'll see below, it was meant to delete one column with a certain name from a worksheet, and I tried to modify it by simply changing the "=" to "<>" and putting an "Or" in to find all the names I want. That didn't work.

    Any help would be appreciated:

    Sub SrmWtrColumnCleanup()
    'Find last column with data in Row 1
     lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
    'Loop through columns, starting at the last one
      For delCol = lastCol To 1 Step -1
    'Delete columns with Name in Row 1
       If Cells(1, delCol) <> "SAMPLENAME" Or "SAMPDATE" Or "METHODCODE" Or "ANALYTE" Or "Result" Or "DL" Or "UNITS" Then _
         Cells(1, delCol).EntireColumn.Delete
      Next
    End Sub
    Last edited by boehmn; 12-23-2010 at 05:58 PM.

  2. #2
    Forum Guru TMS's Avatar
    Join Date
    07-15-2010
    Location
    The Great City of Manchester, NW England ;-)
    MS-Off Ver
    MSO 2007,2010,365
    Posts
    48,303

    Re: Deleting all but a few columns

    Assuming they're the columns you want to keep, one way you can try is:

    Sub SrmWtrColumnCleanup()
    'Find last column with data in Row 1
     lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
    'Loop through columns, starting at the last one
      For delCol = lastCol To 1 Step -1
    'Delete columns with Name in Row 1
       If Cells(1, delCol) <> "SAMPLENAME" _
       And Cells(1, delCol) <> "SAMPDATE" _
       And Cells(1, delCol) <> "METHODCODE" _
       And Cells(1, delCol) <> "ANALYTE" _
       And Cells(1, delCol) <> "Result" _
       And Cells(1, delCol) <> "DL" _
       And Cells(1, delCol) <> "UNITS" _
       Then _
         Cells(1, delCol).EntireColumn.Delete
      Next
    End Sub


    Regards
    Trevor Shuttleworth - Retired Excel/VBA Consultant

    I dream of a better world where chickens can cross the road without having their motives questioned

    'Being unapologetic means never having to say you're sorry' John Cooper Clarke


+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1