添加X行自动填充数据

时间:2016-09-20 12:56:27

标签: excel vba excel-vba

我尝试通过自动填充先前可用的数据来添加数据行。

例如:

在A栏中,从A1开始,有一个标题' Charge 1',然后是A2,' Discharge 1'和A3,' Charge 2& #39;等。

我想在预定的A列中添加预定义的周期数(一个'充电'一个'放电'再多一个'充电')这个系列。

因此,如果A列中的数据以排放5结束,则添加5个周期以填充此数据,直到收费11。

1 个答案:

答案 0 :(得分:0)

在OP的澄清之后

编辑

试试这段代码:

Option Explicit

Sub Cycles()
    Dim cycleStrng1 As String, cycleStrng2 As String
    Dim lastCycle As Long, rowOffset As Long

    With Worksheets("Cycles").Range("A1") ' <--| change "Cycles" to your actual worksheet name
        cycleStrng1 = GetStringAtLeft(.Value)
        cycleStrng2 = GetStringAtLeft(.Offset(1).Value)
        With .End(xlDown)
            lastCycle = GetNumberAtRight(.Value)
            If GetStringAtLeft(.Value) = cycleStrng2 Then rowOffset = 1
            .Offset(rowOffset).Resize(2 * lastCycle) = Application.Transpose(FillCycles(lastCycle, cycleStrng1, cycleStrng2))
        End With
    End With
End Sub

Function GetNumberAtRight(strng As String) As Long
    GetNumberAtRight = CLng(Right(strng, Len(strng) - InStrRev(strng, " ")))
End Function

Function GetStringAtLeft(strng As String) As String
    GetStringAtLeft = Left(strng, InStrRev(strng, " "))
End Function

Function FillCycles(lastCycle As Long, cycleStrng1 As String, cycleStrng2 As String) As Variant
    Dim iCycle As Long
    Dim strng As String

    For iCycle = lastCycle To 2 * lastCycle
        strng = strng & cycleStrng1 & iCycle & "|"
        strng = strng & cycleStrng2 & iCycle & "|"
    Next iCycle
    FillCycles = Split(Left(strng, Len(strng) - 1), "|")
End Function