当一个单元格中有数字时,该单元格内容如何向下移动?

时间:2018-07-13 22:13:13

标签: vba excel-vba

我正在尝试开发一个VBA程序来移动单元格内容,而我只希望使用VBA(想在程序中添加更多内容,并尽可能多地学习VBA)。我需要将内容向下移动一个单元格,但是如果下一个单元格已满而不覆盖它,然后将其向下移动,我不确定程序如何将内容从一个单元格向下移动到下一个单元格。我随附了一张excel表格的jpeg文件。 希望您能提供帮助。

我正在尝试让程序将E1:E12列中的所有数字设置下移。 我需要程序将一组数字(可以是该范围内的一组数字)向下移动到其下方的下一个单元格,并增加该组中的最后一个数字(对计数无限制)。因此,在单元格E1的示例中(8-16)将移动到E2并变为8-17(移动后单元格E1将为空白)。当数字组位于单元格E12中时,它们将移至E1,但仍会增加最后一个数字,并且会不断循环(从E1到E12并返回)。如果下一个单元格已满而不覆盖它,那么程序如何将内容从一个单元格向下移动到下一个单元格,如果有意义的话,如何将其向下移动。一个示例是单元格E12,如果E1已满但必须移动,它将如何移动到E1?

就是这样,非常感谢您的帮助。

my Excel sheet example

2 个答案:

答案 0 :(得分:0)

Sub Tester()

    Dim rng As Range, tmp, i As Long

    Set rng = Range("E1:E12")
    tmp = rng.Cells(rng.Cells.Count).Value
    For i = rng.Cells.Count To 2 Step -1
        rng.Cells(i).Value = Increment(rng.Cells(i - 1).Value)
    Next i
    rng.Cells(1).Value = Increment(tmp)

End Sub

'If value has a dash, increment the second number
'  Assumes any value with a dash has a number on either side...
Function Increment(v)
    Dim rv, arr
    rv = v
    arr = Split(v, "-")
    If UBound(arr) = 1 Then rv = arr(0) & "-" & CLng(arr(1)) + 1
    Increment = rv
End Function

答案 1 :(得分:0)

使用Dictionary对象:

Sub ShiftAndIncrease()
    Dim cell As Range, key As Variant
    With CreateObject("Scripting.Dictionary")
        For Each cell In Range("E1:E12").SpecialCells(xlCellTypeConstants) '
            .Item(cell.Row Mod 12 + 1) = Increase(cell.Value2)
        Next
        Range("E1:E12").ClearContents
        For Each key In .keys
            Range("E" & key).Value = "'" & .Item(key)
        Next
    End With
End Sub

Function Increase(v As Variant)
    Increase = Split(v, "-")(0) & "-" & Split(v, "-")(1) + 1
End Function
相关问题