简体   繁体   中英

Shifting each row differently of a given range with VBA

I have a table with 3 columns and 30 rows. I am trying to write a VBA macro that shifts first row with 1 cell to the right, the second row 2 cells to the right and so on.

For example, this

AAA
BBB
CCC

should look like this:

 AAA
  BBB
   CCC

What I tried so far, could only move the whole selected range:

Sub Macro()
Set Table = Application.InputBox("Select table", Title:="Table", Type:=8)
Table.Cut Table.Offset(0, 1)
End Sub

This should be doing what you want:

Sub Macro()

Set Table = Application.InputBox("Select table", Title:="Table", Type:=8)
Set Dest = Application.InputBox("Select destination", Title:="Destination", Type:=8)

For i = 1 To Table.Rows.Count
    For j = 1 To Table.Columns.Count
         Table.Cells(i, j).Copy Dest.Cells(i + j - 1, i + 1)
    Next j
Next i
End Sub

Before:

在此输入图像描述

The code:

Sub asdfg()
    Dim N As Long, i As Long

    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        Cells(i, 1).Cut (Cells(i, i + 1))
    Next i
End Sub

and after:

在此输入图像描述

EDIT#1:

To shift the entire row use:

Sub zxcvb()
    Dim N As Long, i As Long

    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        Range(Cells(i, 1), Cells(i, i)).Insert Shift:=xlToRight
    Next i
End Sub

Before:

在此输入图像描述

and after:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM