我正在尝试插入具有相应月份和年份标题的列。循环功能正常,我的内部for循环附加年份功能不正常。我明白为什么,这是因为外面没有完整的循环声明。我一直试图找到一种方法来插入检查无济于事,我也找不到在循环之外正确执行它的方法。
简要说明它应该是什么样子: 它目前分为几个季度,所以我试图在每个季度之前插入数月,并附上年份。它看起来像这样,我只是无法将这些年份与正确的列相关联。出于某种原因,它直接跳到20而不是正确填充
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
我还试图在for循环之外做这件事,它只是要重复,所以我每个月都能得到它。
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
答案 0 :(得分:0)
我并不完全了解您要实现的目标,但您目前拥有的代码将始终生成01/01/20, 02/01/20, ...
等值。你的内循环(For i = 13 To 20
)循环总是替换i
,直到它达到20(因为x
没有递增)。
我怀疑你想重新安排你的循环可能是这样的:
For i = 13 To 20
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
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"
End If
Next x
Next i
替代方案可能是这样的:
const intSTART_YEAR As Integer = 13
const intEND_YEAR As Integer = 20
i = intSTART_YEAR
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
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"
i = i + 1
if i > intEND_YEAR then
exit for
end if
End If
Next x