【问题标题】:VBA Excel: Insert a new column every nth column filled with a formula which refrences the immediate column to the leftVBA Excel:每第n列插入一个新列,该列填充一个引用左侧直接列的公式
【发布时间】:2017-01-26 03:09:04
【问题描述】:

我想每隔一列插入一个新列大约 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

【问题讨论】:

  • 在公式中将C3 更改为C[-1]。也就是说,你的公式看起来很可疑。你想让它做什么?
  • 在 R1C1 表示法中,C3 的含义与 $C:$C 在 A1 表示法中的含义相同。 @chrisneilsen 的建议将在公式位于 C 列时生成等效于 B:B,当公式位于 E 列时生成 D:D 等(但正如 Chris 所说,当与行扩展 @987654329 结合使用时,这似乎很可疑@.) 但是,如果您打算 C3 表示左侧一列和放置公式的单元格下方一排的单元格,您也可以只使用 =AVERAGE(R[2]C[-1]:R[3]C[-1]) 的 R1C1 公式并避免 @987654332完全@。
  • @chrisneilsen...我有一个数据集,每个样本有两个测量值(约 100 行),用于约 267 种测量类型(列)。我需要为两次代表提取每种测量类型的平均值,最终我需要将行数减半以仅显示平均值。
  • @YowE3K...我喜欢简化事情,我确实避免了 OFFSET,谢谢!

标签: vba excel


【解决方案1】:

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

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

希望对你有帮助,有任何问题请告诉我

【讨论】:

  • 您缺少H. 对象引用来限定Cells 之一。
  • @FernandoCT...这是您建议的完善代码...谢谢...Sub insert_column_and_Formula() Dim colx As Long Dim H As Worksheet Set H = Sheet1 'Sheet1= Sheet name that contains the data' For colx = 4 To 536 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(41, colx)).FormulaR1C1 = "=AVERAGE(R[0]C[-1]:R[1]C[-1])" 'which is the same as..."=AVERAGE(OFFSET(RC[-1],0,0,2,1))"' Next colx End Sub
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多