VBA复制并粘贴一系列数字

时间:2009-10-14 15:43:52

标签: range copy-paste

我正在尝试复制并粘贴一个范围,以创建一个28乘28的数字网格“旋转”这些值,这样每次将范围粘贴到下一列时,范围向下移动一行,最后一个值“溢出”回到下一行的顶部,我已经走到这一步了但是我在溢出部分难倒(我是VBA的相对新手)

Sub Test()

Dim oRange As Range
Set oRange = ActiveSheet.Range("A1:A28") 

Dim i As Integer
For i = 1 To 28
    oRange.Copy
    oRange.Offset(i, i).PasteSpecial xlPasteAll
Next i

End Sub

另外,我需要复制和粘贴单元格的值和格式

希望你们能提供帮助 感谢

1 个答案:

答案 0 :(得分:1)

Sub Test()

    Dim oRange As Range
    Dim startColumn As String
    Dim rangeStart As Integer
    Dim rangeEnd As Integer
    Dim cellCount As Integer
    Dim i As Integer

    startColumn = "A"
    rangeStart = 1
    rangeEnd = 28
    cellCount = rangeEnd - rangeStart + 1

    For i = 1 To cellCount - 1
        Set oRange = ActiveSheet.Range(startColumn & rangeStart & _
                                ":" & startColumn & (rangeEnd - i))
        oRange.Copy
        oRange.Offset(i, i).PasteSpecial xlPasteAll

        Set oRange = ActiveSheet.Range(startColumn & (rangeEnd - i + 1) & _
                                ":" & startColumn & rangeEnd)
        oRange.Copy
        oRange.Offset((-1 * cellCount) + i, i).PasteSpecial xlPasteAll
    Next i

End Sub

编辑:在索引'i'处插入一个空行:

Rows(i & ":" & i).Select
Selection.Insert Shift:=xlDown

在工作表顶部插入5行,在索引1处插入一行5次:

For i = 1 To 5
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown
Next