我的第一行充满了值。我想在每个这些值之间插入两列,直到第一行中的最后一个非空单元格为止。
我的代码卡在那里了
Sub AddCol()
'
' AddCol Macro
'
For i = 1 To 2
Sheets("CashFlow").Select
Columns(i + 1).Select
Selection.Insert Shift:=x1ToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
End Sub
答案 0 :(得分:2)
几件事。
a)您需要获取列数的值,以便您可以循环遍历并添加
b)循环时,从最高到最低循环,因为如果您从最低到最高循环添加列,则会影响您的计数器,最终您将无法遍历整个标头集。
请参见以下代码:
Sub ColumnsAdd()
Dim lCol As Long
Dim i As Long
Dim myWS As Worksheet
Set myWS = Sheets("CashFlow")
lCol = myWS.Cells(1, myWS.Columns.Count).End(xlToLeft).Column
For i = lCol To 1 Step -1
myWS.Columns(i).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
myWS.Columns(i).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
End Sub
答案 1 :(得分:1)
这将为您工作:
select yyyy, mm, location,
sum(actual_amount) as actual_amount,
sum(plan_amount) as plan_amount
from ((select year(date) as yyyy, month(date) as mm, location,
amount as actual_amount, 0 as plan_amount
from actual
group by year(date) as yyyy, month(date) as mm, location
) union all
(select year, month, location,
0 as actual_amount, amount as plan_amount
from actual
group by year, month, location
)
) ap
group by yyyy, mm, location;
答案 2 :(得分:0)
更简短的方法:
.Columns(i + 1).Resize(, 2).Insert Shift:=x1ToRight, CopyOrigin:=xlFormatFromLeftOrAbove