在活动单元格右侧插入一列,并从前一列自动填充公式

我是新来的这个论坛和VBA,所以如果这需要澄清,只是让我知道,我提前道歉!

我正在尝试使用VBA在活动单元格的右侧插入新列,并使用左侧相邻列中的所有公式格式化新列。 我可以通过使用复制和粘贴function来做到这一点,但运行代码时,Excel非常慢。

Sub MyInsertColumn() Selection.EntireColumn.Offset(0, 1).Insert Shift:=xlToRight, CopyOrigin:=xlFormatRightOrAbove Cells(6, ActiveCell.Column -1).Copy Cells(6, ActiveCell.Column).Select ActiveSheet.Paste Cells(7, ActiveCell.Column -1).Copy Cells(7, ActiveCell.Column).Select ActiveSheet.Paste Cells(8, ActiveCell.Column -1).Copy Cells(8, ActiveCell.Column).Select ActiveSheet.Paste Application.CutCopyMode = False End Sub 

此代码也不会格式化新的所需的列,除非我运行代码两次,并已插入另一列。

我想能够使用代码的一系列行。 例如从6到24。

我完全不理解你的问题,但似乎这是你需要的代码

 Selection.EntireColumn.Offset(0, 1).Insert Shift:=xlToRight Range(Cells(6, Selection.Column), Cells(24, Selection.Column)).Select Selection.Copy Selection.Offset(0, 1).PasteSpecial (xlPasteFormulasAndNumberFormats) Application.CutCopyMode = False 

我让它变得简单易懂。 我build议按F8并逐行运行代码以了解它是如何工作的

使用正确的XlInsertFormatOrigin枚举和FillRight。

 Option Explicit Sub MyInsertColumn() With Selection.EntireColumn.Offset(0, 1) .Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightOrBelow .Offset(0, -1).Cells(6, 1).Resize(3, 1).FillRight End With End Sub 

这假设你是在你想要复制公式的列上的某个地方。