VBA Excel:每n列插入一个新列,该列填充了一个公式,该公式引用了左侧的直接列



我想每隔一列插入一个新列大约 260 次,然后我需要用引用左侧直接列的公式填充新列。这是我必须插入一个新列的内容:

Sub insert_column_every_other()
For colx = 2 To 266 Step 2
Columns(colx).Insert Shift:=xlToRight
Next
End Sub

但我被困在公式上,它只是按原样复制公式。我需要 C3 值来更改并引用左侧的直接列(其他部分可能不是 100% 我是 VBA 的新手,因此感谢所有更正):

Sub Repeat()
For ColNum = 3 To 2000 Step 2
    Range(Cells(2, ColNum), Cells(21, ColNum)).FormulaR1C1 ="=AVERAGE(OFFSET(C3,1,0,2,1))"
Next ColNum
End Sub

我认为下一个代码应该做你想要的

Sub insert_column_and_Formula()
   Dim colx As Long
   Dim H As Worksheet
   Set H = H3 'Replace H3 with the sheet that contains your data
   For colx = 2 To 266 Step 2
      'Insert the Column' 
      Call H.Columns(colx).Insert(Shift:=xlToRight)
      'Put the formula in the new Column'
      H.Range(H.Cells(2, colx), H.Cells(21, colx)).FormulaR1C1 = "=AVERAGE(OFFSET(RC[-1],1,0,2,1))"
   Next colx
End Sub

希望这对您有所帮助,任何问题请告诉我

最新更新