插入引用备用列的Excel公式

我试图在连续的列中插入下面的公式='外部成本B0'!F73在工作表的同一行中,但是在工作表“外部成本”中的单元格引用“F73”指的是交替列,例如F73,H73, J73,L73等

这是电子表格的公式注释屏幕截图

公式表的屏幕截图

这是我试过的代码,但我正在努力想办法让替代列参考工作。

Dim CostColumns As Long 

'select单元格开始从中插入公式

 Range("E26").Select 

'从“外部成本B0”表中的列F(6)开始,并进入每个备用列

 For CostColumns = 6 To 600 Step 2 ActiveCell.Formula = "= ""'External Costs B0'!"" & Rows(73)Columns(CostColumns)" 

移至下一个单元格以插入公式,并将列引用前进2列

  ActiveCell.Offset(0, 1).Select Next CostColumns 

最终的结果是我在许多post中看到的错误:

应用程序定义或对象定义的错误。

这里有很多其他语法的公式插入我试过没有成功。 任何帮助是极大的赞赏。 根据上述示例,下面的内容是指外部成本B0表中的第40行而不是第73行。

 Range("E26").Select For CostColumns = 6 To 66 Step 2 'ActiveCell.FormulaR1C1 = "= worksheets("""External Costs B0""").Cells(40,6).Value" 'ActiveCell.FormulaR1C1 = "='External Costs B0'!R[14]C[CostColumns]" 'Range("E26:AK26").FormulaR1C1 = "='External Costs B0'!R[14]C[CostColumns]" 'ActiveCell.FormulaR1C1 = "= worksheets('External Costs B0')!" & " Rows(40)Columns(CostColumns)" 'Range("E26:AK26").FormulaR1C1 = "='External Costs B0'!R[14]C[+2]" 'Range("E26:AK26").FormulaR1C1 = "=Wksht.Cells(40,CostColumns) &" 'Range("E26:AK26").Formula = "=worksheets('External Costs B0'!)" & ".Cells(40,6)" 'ActiveCell.Formula = "= worksheets('External Costs B0'!).Cells(40,6).Value" ActiveCell.Offset(0, 1).Select Next CostColumns 

用这个:

 ActiveCell.Formula = "='External Costs B0'!" & Cells(73, CostColumns).Address(0, 0) 

问题是,行(73)和列(CostColumns)都返回一个Range对象,你不能连接到一个string。

这段代码将把你的公式放在单元格Sheet1!A1:AD1

A1的公式是='External Costs B0'!$A$73
在B1中,它将是='External Costs B0'!$C$73等等,直到='External Costs B0'!$BG$73在单元格AD1

 Sub PasteFormula() Dim CostColumns As Long Dim y As Long 'Starting column for External Costs reference CostColumns = 1 With ThisWorkbook.Worksheets("Sheet1") For y = 1 To 30 .Cells(1, y).FormulaR1C1 = "='External Costs B0'!R73C" & CostColumns CostColumns = CostColumns + 2 Next y End With End Sub 
  • 将代码更改Sheet1更新为需要公式显示的任何表单。
  • CostColumn=1更改为您希望公式引用的正确列号。
  • y = 1 To 30更改y = 1 To 30以使公式出现在正确的列中。

代码使用R1C1语法,因为如果只需处理行和列号,则更容易更新公式。例如, R 73 C 2是第73行,第2列。

它的方式更容易,如果你使用FormulaR1C1和没有select像下面的子:(请更改R,RowOffset和公式UnicenterColumn您的需要)

 Sub Formulas() Dim I As Integer Const R As Long = 9 'row Const RowOffset As Integer = -8 Const ForumulaUntilColumn As Long = 7 For I = 1 To ForumulaUntilColumn Cells(R, I).FormulaR1C1 = "=R[" & RowOffset & "]C[" & I - 1 & "]" Next I End Sub 

PS:在'='和'R [''之间的任何其他公式中添加工作簿和表名称