Consulting

Results 1 to 3 of 3

Thread: How can I write a loop to clear cells evenly spaced apart?

  1. #1
    VBAX Newbie
    Joined
    Aug 2011
    Posts
    1
    Location

    How can I write a loop to clear cells evenly spaced apart?

    Hi guys, I'm getting back into VBA again and I have a task. I need to clear cells that are evenly distance apart. In my eample code, they are 4 columns apart. Basically, I would like a loop to do this for 200 columns or so.

    Here is the manual way I am doing it now. Thanks!

    [VBA]
    Range("A4:A20").Select
    Selection.ClearContents
    Range("E4:E20").Select
    Selection.ClearContents
    Range("I4:I20").Select
    Selection.ClearContents
    Range("M4:M20").Select
    Selection.ClearContents
    [/VBA]

  2. #2
    Knowledge Base Approver VBAX Guru GTO's Avatar
    Joined
    Sep 2008
    Posts
    3,368
    Location
    Not well though through, but maybe something like:
    [VBA]Option Explicit

    Sub exa()
    BuilRange(1, 200, 4, 4, 20, Sheet1).ClearContents
    End Sub

    Function BuilRange(FirstCol As Long, _
    LastCol As Long, _
    Interval As Long, _
    FirstRow As Long, _
    LastRow As Long, _
    wks As Worksheet _
    ) As Range
    Dim i As Long
    Dim rng As Range

    Set rng = Range(wks.Cells(FirstRow, FirstCol), wks.Cells(LastRow, FirstCol))

    For i = FirstCol + Interval To LastCol Step Interval
    Set rng = Application.Union(rng, Range(wks.Cells(FirstRow, i), wks.Cells(LastRow, i)))
    Debug.Print rng.Address
    Next

    Set BuilRange = rng
    End Function[/VBA]
    Hope that helps,

    Mark

  3. #3
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    You could also use a simple loop:
    [VBA]
    Dim lngCol As Long
    For lngCol = 1 To 200 Step 4
    Range(Cells(4, lngCol), Cells(20, lngCol)).ClearContents
    Next lngCol
    [/VBA]
    Be as you wish to seem

Posting Permissions

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