I have a range selected in a single row and have a code which I want to loop through every odd cell in that range. Let's say the range is of 20 cells. I want the loop to act on cell no. 1,3,5 and so on. Which loop would be best and what's the syntax?
CodePudding user response:
Using Step in a For...Next Loop
The Code
Option Explicit
Sub EveryOther()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim rg As Range: Set rg = ws.Range("D1:Z1")
' Or:
'Set rg = Selection
'Set rg = Selection.Rows(1)
Dim c As Long
Debug.Print "ColumnIndex", "ColumnAddress"
For c = 1 To rg.Columns.Count Step 2 ' every other cell
' Do your thing, e.g.:
Debug.Print c, rg.Columns(c).Address(0, 0)
Next c
End Sub
Results in the Immediate window (Ctrl G)
ColumnIndex ColumnAddress
1 D1
3 F1
5 H1
7 J1
9 L1
11 N1
13 P1
15 R1
17 T1
19 V1
21 X1
23 Z1
CodePudding user response:
Try This!
Sub SkipColumn()
Dim ColNum As Integer, RowNum As Integer
RowNum = 1
For ColNum = 1 To 26 Step 2
If Cells(RowNum, ColNum).Value = "" Then
Cells(RowNum, ColNum).Value = "Hello"
End If
Next ColNum
End Sub