如何基于上一行数据在Excel中自动添加新行

时间:2018-11-09 16:38:16

标签: excel database vba excel-formula excel-2010

好的,我认为这需要VBA代码。

Here is how my file looks like

我想每年自动添加一个新行,因此文件to look like this

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

相当罗Pre,但可以正常工作...我可以肯定,有很多有效的方法可以完成它,但是在这里

Sub sorter()

    Dim row As Long: row = 2
    Dim lastRow As Long
    Dim yearList As Variant
    Dim year As Variant
    Dim extra As Integer: extra = 0
    Dim numYears As Integer

    With ThisWorkbook.Worksheets("your sheet name")
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).row

        Do While True
            yearList = Split(CStr(.Range("C" & row)), "|")
            numYears = UBound(yearList) - LBound(yearList) + 1

            If numYears > 1 Then
                For Each year In yearList
                    .Cells(row + extra, 1).Value = .Cells(row, 1).Value
                    .Cells(row + extra, 2).Value = .Cells(row, 2).Value
                    .Cells(row + extra, 3).Value = year

                    ' for cols D-F
                    .Cells(row + extra, 4).Value = .Cells(row, 4).Value
                    .Cells(row + extra, 5).Value = .Cells(row, 5).Value
                    .Cells(row + extra, 6).Value = .Cells(row, 6).Value

                    If extra = numYears - 1 Then Exit For

                    .Cells(row + extra + 1, 1).EntireRow.Insert
                    extra = extra + 1
                Next year
                extra = 0
            End If
            row = row + 1
            If Len(CStr(.Range("A" & row))) = 0 Then Exit Do
        Loop
    End With
End Sub

答案 1 :(得分:0)

非常简单 您想分割年份,如果尚未分割的话

dim year_string() as string
rowint = 2
year_string = split([insert your cell address],"|")
for each year in year_string
    cells(rowint, 1).value2 = [insert your cell address]
    cells(rowint, 2).value2 = [insert your cell address]
    cells(rowint, 3).value2 = year
next year