VBA Excel: Insert a new column every nth column filled with a formula which refrences the immediate column to the left

寵の児 提交于 2020-01-07 02:31:07

问题


I would like to insert a new column every other column about 260 times, then I need to fill the new columns with a formula which references the immediate column to the left. Here is what I have to insert a new column:

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

But I am stuck on the formula, it merely copies the formula as is.. I need the C3 value to change and reference the immediate column to the left (other parts might not be 100% I am new to VBA so all corrections are appreciated):

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

回答1:


I think the next code should do what you want

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

Hope this help you, any question let me know please



来源:https://stackoverflow.com/questions/41865318/vba-excel-insert-a-new-column-every-nth-column-filled-with-a-formula-which-refr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!