使用Excel VBA向右移动列数据

use*_*125 1 excel vba excel-vba

以下是我的excl数据:

A    B       c  .... F               G

1   test    vb1     testing1        open
2   test1   vb2     testing1        close
2   test2   vb3     testing1 
4   test3   vb4     testing1
Run Code Online (Sandbox Code Playgroud)

我想将F列数据移动到B列并将B列数据移到右边,所以在B之前将是C.

如何使用Excel VBA编程来完成此操作.

谢谢,

Chaitu

JMa*_*Max 9

试试这个:

Option Explicit

Sub MoveColumns()

With ActiveSheet
    .Columns("F:F").Cut
    .Columns("B:B").Insert Shift:=xlToRight
    .Columns("C:C").Cut
    .Columns("E:E").Insert Shift:=xlToRight
End With
Application.CutCopyMode = False
End Sub
Run Code Online (Sandbox Code Playgroud)

要使用它:

  • 打开Visual Basic编辑器:工具>宏> Visual Basic编辑器
  • 插入模块(右键单击VBAProject并插入>模块)
  • 将上述代码粘贴到此新模块中.

然后,您可以从Excel执行代码:工具>宏...>宏...

[编辑]另一个没有复制粘贴的尝试

Option Explicit

Sub copyWithArray()
Dim lLastrow As Long
Dim aValues As Variant

With ActiveSheet
    lLastrow = .Cells(.Rows.Count, "AE").Row
    'store data from the column F
    aValues = .Range("F1:F" & lLastrow).Value
    '"move" data a column further
    .Range("C1:AE" & lLastrow).Value = .Range("B1:AD" & lLastrow).Value
    'copy data from column C to column B
    .Range("B1:B" & lLastrow).Value = .Range("C1:C" & lLastrow).Value
    'restore data copied from column F to column B
    .Range("B1:B" & lLastrow).Value = aValues
End With
End Sub
Run Code Online (Sandbox Code Playgroud)