-
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]
-
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
-
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]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules