Excel宏:插入列并从相邻列复制公式

时间:2016-03-17 10:35:59

标签: excel vba excel-vba macros

我正在尝试将一个列插入到工作表中,并将公式从相邻的列复制到右侧。

正在从工作表本身读取插入列的位置。 E.G栏S(第19栏)。

所以我需要在Column" S"并复制" Old"列S,现在是第T列。

我使用以下代码,但它给了我1004错误。

 Sub Insert_Rows_Loop()
      Dim CurrentSheet As Object
      'MsgBox "ghj" & Sheet16.Range("H2").Value
      Sheet2.Cells(1, Sheet16.Range("H2").Value).EntireColumn.Select
      Selection.Copy
      Selection.Insert Shift:=xlToLeft
      Application.CutCopyMode = False

      Sheet2.Cells(1, Sheet16.Range("G2").Value).EntireColumn.Select
      Selection.Copy
      Selection.Insert Shift:=xlToLeft
      Application.CutCopyMode = False

      Sheet2.Cells(1, Sheet16.Range("F2").Value).EntireColumn.Select
      Selection.Copy
      Selection.Insert Shift:=xlToLeft
      Application.CutCopyMode = False
 End Sub

2 个答案:

答案 0 :(得分:0)

以下代码将执行以下操作:

  

在当前列S的左侧插入一个新列   将列S中的公式设置为列T(旧列S)中的公式到列S

  Dim CurrentSheet As Worksheet
  Set CurrentSheet = ThisWorkbook.Sheets("Sheet1")

 With CurrentSheet
      'Inserting the Column before Column S
      .Range("S1").EntireColumn.Insert
      'Copying the Formulas from the T(Old S) to S
      .Range("S1").EntireColumn.Formula = .Range("T1").EntireColumn.Formula
 End With

您需要调整Range中的值以满足您的要求,Sheet参考会有所不同。

我希望你能理解它背后的想法。

答案 1 :(得分:0)

您的示例代码表示在依赖.Select.Activate方法导航和引用工作簿中的各种单元格和工作表时遇到的问题。避免。选择和。激活有利于直接细胞参考¹。

第二个问题是没有预定的列插入顺序。当可以以看似随机的顺序插入列时,如果列号有升序模式,则当列先前插入到其右侧时,后面的列将更改位置。 “最佳实践”是从右侧开始插入列并向A列方向工作。

以下内容基于您的示例代码所说的内容,因为它不会像您的叙述那样遵循相同的流程。

Sub Insert_Rows_Loop()
    Dim c As Long, arr As Variant

    With Sheet16
        ReDim arr(2)
        'get them in descending order so that inserting 1 does not change the position of 2 or 3
        arr(0) = Application.Large(.Range("F2:H2"), 1)
        arr(1) = Application.Large(.Range("F2:H2"), 2)
        arr(2) = Application.Large(.Range("F2:H2"), 3)
    End With

    With Sheet2
        For c = LBound(arr) To UBound(arr)
            With .Columns(arr(c))
                .Copy
                .Insert Shift:=xlToLeft
            End With
        Next c
    End With

    Application.CutCopyMode = False
 End Sub

¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros