选择,插入,剪切,粘贴所有工作表都会出错

时间:2012-02-16 04:02:14

标签: excel vba loops

我想把这个vba执行循环到所有工作表。显然,它只能管理当前活动的工作表。它无法为其他工作表重复此操作。为什么呢?

Sub adjustcolumns1()
 Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets

    Columns("B:B").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Columns("D:D").Select
    Selection.Cut
    Columns("B:B").Select
    ActiveSheet.Paste
    Columns("D:D").Select
    Selection.Delete Shift:=xlToLeft
    Columns("H:H").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Columns("J:J").Select
    Selection.Cut
    Columns("H:H").Select
    ActiveSheet.Paste
    Columns("J:J").Select
    Selection.Delete Shift:=xlToLeft
Next ws

End Sub

1 个答案:

答案 0 :(得分:1)

您无法在不可见的工作表上“选择”...但您不想“选择”,这是一种从不编辑录制的宏中学到的坏习惯。因此,让我们调整您的宏以直接将命令发送到所需的范围而不选择,然后将这些命令绑定到工作表循环。

Option Explicit

Sub AdjustColumns1()
Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        ws.Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        ws.Columns("D:D").Copy ws.Range("B1")
        ws.Columns("D:D").Delete Shift:=xlToLeft
        ws.Columns("H:H").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        ws.Columns("J:J").Copy ws.Range("H1")
        ws.Columns("J:J").Delete Shift:=xlToLeft
    Next ws

End Sub

我们可以真正缩短这一点:

Option Explicit

Sub AdjustColumns1()
Dim ws As Worksheets

    For Each ws In ActiveWorkbook.Worksheets
        ws.Columns("C:C").Cut
        ws.Columns("B:B").Insert Shift:=xlToRight
        ws.Columns("J:J").Cut
        ws.Columns("I:I").Insert Shift:=xlToRight
    Next ws

End Sub