I'm trying to insert columns with the appropriate month and year heading. The loop functions correctly, my inside for loop that attaches the year isn't functioning properly. I understand why, it's because there is no full loop on the outside for statement. I've been trying to find a way to insert checks to no avail, and nor can I find a way that does it outside of the loop properly.
Brief explaination of what it should look like: It's seperated into quarters currently, so I'm trying to insert months before each quarter, with the year attached. It looks like this, I just can't get the years to associate to the correct columns. For some reason it skips straight to 20 as opposed to filling correctly
Col1 Col2 Col3 Col4 Col5 Col6 ....Colx
Row 1 01/13 02/13 03/13 Q1 04/13 05/13....01/14
Row 2
Sub Months()
'Inserts month headings for vlookup quantity information
Dim y As String
y = "Q1"
If y = "" Then Exit Sub
Dim x As Long
For x = Cells(1, Columns.Count).End(xlUp).Column To 1 Step -1
If Cells(1, x).value = y Then
Columns(x).EntireColumn.Insert
Columns(x).EntireColumn.Insert
Columns(x).EntireColumn.Insert
For i = 13 To 20
Cells(1, x).value = "01/01/" & i
Cells(1, x).NumberFormat = "mm-yy"
Cells(1, x + 1).value = "02/01/" & i
Cells(1, x + 1).NumberFormat = "mm-yy"
Cells(1, x + 2).value = "03/01/" & i
Cells(1, x + 2).NumberFormat = "mm-yy"
Next i
End If
Next x
Dim y2 As String
y2 = "Q2"
If y = "" Then Exit Sub
Dim x2 As Long
For x2 = Cells(1, Columns.Count).End(xlUp).Column To 1 Step -1
If Cells(1, x2).value = y2 Then
Columns(x2).EntireColumn.Insert
Columns(x2).EntireColumn.Insert
Columns(x2).EntireColumn.Insert
For i2 = 13 To 20
Cells(1, x2).value = "04/01/" & i2
Cells(1, x2).NumberFormat = "mm-yy"
Cells(1, x2 + 1).value = "05/01/" & i2
Cells(1, x2 + 1).NumberFormat = "mm-yy"
Cells(1, x2 + 2).value = "06/01/" & i2
Cells(1, x2 + 2).NumberFormat = "mm-yy"
Next i2
End If
Next x2
I'm also including my attempt to do it outside of the for loop, it's just going to have to repeat so I can get each month.
Sub replace()
'Adds year
Dim Name As String
Name = "1/1/"
LR = Range("1:1" & Cells(1, Columns.Count).End(xlLeft).Column)
For Each c In LR
For i = 13 To 20
If Cells(1, c.Column) = Name Then
Cells(1, c.Column) = Name & i
End If
Next i
Next
End Sub
I don't fully understand what you are trying to achieve but the code you currently have will always produce values such as
01/01/20, 02/01/20, ...
. Your inner loop (For i = 13 To 20
) loops always replacingi
until it hits 20 (asx
isn't being incremented).I suspect you want to re-arrange your loops to maybe something like this:
An alternative could be something like this: