Consulting

Results 1 to 5 of 5

Thread: How to add a column to a collection

  1. #1
    VBAX Regular
    Joined
    Sep 2006
    Posts
    65
    Location

    How to add a column to a collection

    Hi

    Hello

    I need to delete columns that doesn't contain data, and in order to do that. I believe I first have to create a collection og those columns that doesn't contain data. This is what I've come up with so far but unfortunately it doesn't work:

    [vba]
    dim s as collection
    For i = 1 To r

    If WorksheetFunction.Sum(Range(Cells(2, i + 1), Cells(p + 1, i + 1))) = 0 Then
    s.Add (Columns(i + 1))
    End If
    Next i

    For Each comlumns In s
    Columns.Delete Shift:=xlToLeft
    Next[/vba]

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    You don't need a collection, in fact it must be the last thing you need, you can either delete inline, or else accumulate the rows and delete.

    But what is r, what is p, and what is the condition that triggers the delete?

  3. #3
    VBAX Regular
    Joined
    Sep 2006
    Posts
    65
    Location
    p is the number of rows and r is the number of columns.

    If a column sums to zero it must be deleted.

    I don't know what it means to delete inline or how to accumulate the columns.

  4. #4
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    This will delete the columns to the extent of the range. If you want the whole column deleted, let us know.
    [VBA]Sub DelCols()
    For i = r To 1 Step -1
    If WorksheetFunction.Sum(Range(Cells(2, i + 1), Cells(p + 1, i + 1))) = 0 Then
    Range(Cells(2, i + 1), Cells(p + 1, i + 1)).Delete shift:=xlToLeft
    End If
    Next
    End Sub
    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  5. #5
    VBAX Regular
    Joined
    Sep 2006
    Posts
    65
    Location
    Thanks.

    I ended up using the union() function instead.

Posting Permissions

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