2016-03-17 46 views
0

我试图插入一列到工作表中,并将公式从相邻的列复制到右边。Excel宏:插入列并将公式从相邻列复制到它

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

所以我需要在Column“S”插入一个新列,然后从“老”栏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 
+1

欢迎来到Stackoverflow。请不要指出,这不是一个代码编写网站,人们要求为他们开发代码。你要求的是非常简单的。尝试使用Macro记录器并在“S”之前插入“Column”,然后复制数据,然后在此处发布该代码并查看我们可以提供的帮助。这样你就可以避免因为没有代码的问题而导致投票失败。祝你好运,享受Stackoverflow! –

回答

0

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

插入新列到当前列左边小号
坐落在列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引用会有所不同。

我希望你能明白它背后的想法。

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更多的方法从依靠选择越来越远,并激活,以实现自己的目标。

相关问题