+ Reply to Thread
Results 1 to 7 of 7

Looping thru columns for value

Hybrid View

  1. #1
    Registered User
    Join Date
    11-14-2013
    Location
    New York
    MS-Off Ver
    Excel 2010
    Posts
    96

    Looping thru columns for value

    Hello!

    In range("A2:Z20"), im trying to loop thru each column for cells containing a specific name ("joe dirt")
    How can i loop thru these columns, and if the column doesnt contain the name id delete it.

    Ive been experimenting & keep fumbling over multiple for loops. I figured id throw it out there, since this is the land of speedy experts. help me think on the right track, thank you in advance!!!

  2. #2
    Forum Contributor
    Join Date
    02-26-2014
    Location
    USA
    MS-Off Ver
    Excel 2010
    Posts
    173

    Re: Looping thru columns for value

    A somewhat slower implementation but simple enough that it should work

    Dim rCells As Range
    Dim rCell As Range
    
    Set rCells = ActiveSheet.Range("A2:Z20")
    For Each rCell In rCells
        If rCell.Value <> "joe dirt" Then
            rCell.EntireColumn.Delete
        End If
    Next rCell
    Edit: Misread column as row
    Last edited by smpita; 11-09-2017 at 04:04 PM.

  3. #3
    Registered User
    Join Date
    11-14-2013
    Location
    New York
    MS-Off Ver
    Excel 2010
    Posts
    96

    Re: Looping thru columns for value

    Thanks for the quick reply. Let me throw a scenario at you...

    I want to delete the column, and the column is comprised of dates. so just because the name doesnt appear on monday, doesnt mean i delete the entire column because it might appear just once at the end of the month. The entire column has to be blank in order to delete it.

    Update-question.
    I tried using a .Find method, as if i were looking thru the column for "joe dirt", then loop to next column. (however i couldnt make it work)
    Last edited by Quint6778; 11-09-2017 at 04:09 PM.

  4. #4
    Forum Contributor
    Join Date
    02-26-2014
    Location
    USA
    MS-Off Ver
    Excel 2010
    Posts
    173

    Re: Looping thru columns for value

    I'm not quite clear on what you're trying to achieve. Here is a copy of one of my primary search functions, it may be helpful to you.

    Use like this to return the string name of the range of all cells that loosely contain the string "joe dirt". Note, with explicit false it turn off case sensitivity and search within strings. It would match "Joe Dirty 11/16/2017" The return might look like the string "A2:Z20"

    Dim sJoeDirts as String
    sJoeDirts = findCell("joe dirt", 0, , , False)
    Use like this to return the first cell address that strictly contains the word "joe dirt". It will not match "Joe dirt". If "joe dirt" is not found, it will return the string "NotFound"

    Dim sJoeDirt as String
    sJoeDirt = findCell("joe dirt", 1, , , True)
    Public Function findCell(searchString As String, Instance As Long, Optional xOffset As Integer, Optional yOffset As Integer, Optional Explicit As Boolean) As String
    
    '   Returns the cell address of the Nth instance of a word.
    
        Dim searchMatches()
        Dim searchMatch
        Dim firstMatch
        Dim Index As Long
        Dim upBound As Long
        Dim findAll As Boolean
        Dim findAllRange As Range
        Dim SD
        Dim LA
        Dim MC As Boolean
    
        SD = xlNext
        findAll = False
        If Instance < 0 Then
            SD = xlPrevious
            Instance = Instance * -1
        ElseIf Instance = 0 Then ' If instances are 0, we want all matches.
            findAll = True
            Instance = Application.WorksheetFunction.CountIf(myWorksheet.Cells, searchString)
        End If
        
        If Explicit Then
            LA = xlWhole
            MC = True
        Else
            LA = xlPart
            MC = False
        End If
        Index = 0
    
    '   Search A1 first...
        Set searchMatch = myWorksheet.Range("A1").Find(what:=searchString, LookIn:=xlFormulas, _
                                                LookAt:=LA, SearchOrder:=xlByRows, SearchDirection:=SD, _
                                                MatchCase:=MC, SearchFormat:=False)
    '   If we didn't find our first match in A1, then search on!
        If searchMatch Is Nothing Then
            Set searchMatch = myWorksheet.Cells.Find(what:=searchString, After:=myWorksheet.Range("A1"), LookIn:=xlFormulas, _
                                                    LookAt:=LA, SearchOrder:=xlByRows, SearchDirection:=SD, _
                                                    MatchCase:=MC, SearchFormat:=False)
        End If
        Set firstMatch = searchMatch ' Store first match
        If findAll Then Set findAllRange = searchMatch ' Store in set if wanting all matches
    
        Do Until Index = Instance ' Loop until we've found requested instance
            If Not searchMatch Is Nothing Then 'If we found something
                upBound = upBound + 1
                ReDim Preserve searchMatches(upBound) ' Make room in array for it
                
                searchMatches(Index) = searchMatch.offset(yOffset, xOffset).Address(False, False) ' Store address in array
                  
                If Instance > Index + 1 Then
                    Set searchMatch = myWorksheet.Cells.Find(what:=searchString, After:=searchMatch, LookIn:=xlFormulas, _
                                                        LookAt:=LA, SearchOrder:=xlByRows, SearchDirection:=SD, _
                                                        MatchCase:=MC, SearchFormat:=False) ' Search again if more are requested
    
                    If searchMatch.Address = firstMatch.Address Then ' If we loop back to first address
                        findCell = "TooMany"
                        If findAll Then findCell = findAllRange.Address
                        Exit Function
                    End If
                    
                    If findAll Then Set findAllRange = Union(findAllRange, searchMatch)
                End If
            End If
    
            Index = Index + 1
        Loop
        
        If firstMatch Is Nothing Then
            findCell = "NotFound"
            Exit Function
        End If
            
        If findAll Then
            findCell = findAllRange.Address
        Else
            findCell = searchMatches(Instance - 1)
        End If
    
    End Function
    Last edited by smpita; 11-09-2017 at 04:25 PM. Reason: TypeName(Me) used in the debug.print lines will break in some contexts. Removed for portability.

  5. #5
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 Version 2406 Win 11 Home 64 Bit
    Posts
    24,001

    Re: Looping thru columns for value

    This may work, if I am understanding your issue correctly

    Option Explicit
    
    Sub JoeDirt()
        Dim i As Long, lr As Long, lc As Long
        lc = Cells(1, Columns.Count).End(xlToLeft).Column
        For i = lc To 1 Step -1
            lr = Cells(Rows.Count, i).End(xlUp).Row
            If Application.WorksheetFunction.CountA(Range(Cells(1, i), Cells(lr, i))) = 0 Then
                Cells(1, i).EntireColumn.Delete
            End If
        Next i
    End Sub
    Alan עַם יִשְׂרָאֵל חַי


    Change an Ugly Report with Power Query
    Database Normalization
    Complete Guide to Power Query
    Man's Mind Stretched to New Dimensions Never Returns to Its Original Form

  6. #6
    Registered User
    Join Date
    11-14-2013
    Location
    New York
    MS-Off Ver
    Excel 2010
    Posts
    96

    Re: Looping thru columns for value

    This is exactly what i was looking for. Havent tested, but i'll make it work. i didnt even think of the COUNT function... thank you! and thank you smpita as well!

  7. #7
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 Version 2406 Win 11 Home 64 Bit
    Posts
    24,001

    Re: Looping thru columns for value

    You are welcome. Thanks for the rep.

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. [SOLVED] Looping through .Columns
    By efarkouh in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 04-21-2017, 02:01 PM
  2. [SOLVED] Looping through columns
    By Peterhmg in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 06-09-2016, 08:34 AM
  3. [SOLVED] Looping through columns
    By kosherboy in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 03-21-2016, 02:10 PM
  4. looping through columns
    By ammartino44 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 06-03-2015, 08:59 PM
  5. Looping through columns
    By figuraluk in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 10-20-2013, 01:06 PM
  6. Do Until Looping (not looping through all other columns)
    By orle8050 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 02-11-2013, 10:37 AM
  7. [SOLVED] Looping thru columns
    By Robert in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 06-15-2005, 05:05 AM

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