根据AA列中的日期(月)将费用数据从列K:M移动到相应的列N:Y(1月,2月,3月等),但是AA列中的任何未来日期都填充了未来(前进)而不是历史上所希望的?
Sub MoveData()
Dim vals As Range, val As Range, colOffset As Integer
Set vals = Range("K2:K" & Range("K2").End(xlDown).Row)
For Each val In vals
If val > 0 Then
colOffset = VBA.month(val.offset(0, 16))
val.offset(0, colOffset) = val
val.offset(0, colOffset + 1) = val.offset(0, 1)
val.offset(0, colOffset + 2) = val.offset(0, 2)
End if
Next val
End Sub
答案 0 :(得分:1)
在OP的进一步规范之后编辑
不确定我是否掌握了你需要的逻辑,但试试这个
选项明确
Sub MoveData()
Dim colOffset As Integer, dataCols As Long
Dim datesRng As Range, dateRng As Range, valsRng As Range
With ThisWorkbook.Worksheets("expenses") '<== change it to your actual sheet name
Set datesRng = .Range("AA2:AA" & .Cells(.rows.Count, "AA").End(xlUp).Row).SpecialCells(xlCellTypeConstants, xlNumbers) 'process rows as long as there's a "Transition Date"
For Each dateRng In datesRng
With .Range("K" & dateRng.Row)
dataCols = WorksheetFunction.CountA(.Resize(, 3))
Set valsRng = .Offset(, 3 - dataCols).Resize(, dataCols)
End With
colOffset = WorksheetFunction.Min(Month(dateRng), Month(Date)) - dataCols 'limit month offset to current one and set it back to the numbers of values
If colOffset >= 0 Then
.Range("N" & dateRng.Row).Offset(, colOffset).Resize(, dataCols).Value = valsRng.Value
.Range("N" & dateRng.Row).Offset(, colOffset).Value = .Range("N" & dateRng.Row).Offset(, colOffset) - .Range("J" & dateRng.Row).Value
Else
'some K-L columns data would be overwritten!!
End If
Next dateRng
End With
End Sub