【问题标题】:1004 Error - Dynamically Assigning Formula to a Range of Cells1004 错误 - 将公式动态分配给单元格区域
【发布时间】:2012-04-23 02:41:27
【问题描述】:

我正在尝试动态设置在执行宏时输入公式的单元格。这段代码将循环大约 10 次,每次都有一个新的员工部分。由部门订购。所以当循环回到这一点时,第一个单元格将发生变化。

我得到这个错误:

对象“_Global”的方法“范围”失败

这是我的代码:

'Select the top cell in the "%Working" Column

Range(Cells(StartTemp, 9)).Select

'Insert the Formula - Billable/(Billable + Unbillable) * 100 into Column I for each section
'Formula is 'C4/(C4+C5)*100

Range(Cells(StartTemp, 9)).Formula = "=RC[-6]/(RC[-6]+RC[-5]) *100" 
Range(Cells(StartTemp, 9)).Select
Selection.NumberFormat = "0.00%"

'Insert the Formula into all cells in the section for this group.

Selection.AutoFill Destination:=Range(Cells(StartTemp, 9), Cells(EndTemp, 9)), Type:=xlFillDefault    

Range(Cells(StartTemp, 9), Cells(EndTemp, 9)).Select

提前致谢!

【问题讨论】:

  • 哪一行报错?
  • 错误信息的内容是什么? (1004 至少有两个不同的)。

标签: vba excel excel-2007 range formula


【解决方案1】:

您收到该错误是因为您使用的是Range(Cells(StartTemp, 9))

RangeCells 一起使用时,您不能只使用一个单元格。语法是

范围(Cell1,Cell2)

这会给你一个你得到的错误:)

Msgbox Range(Cells(1, 1)).Address 

还要避免使用.Select。它们也是导致错误的主要原因。

将您的代码更改为此并重试(未测试

With Cells(StartTemp, 9)
    .Formula = "=RC[-6]/(RC[-6]+RC[-5]) * 100"
    .NumberFormat = "0.00%"
    .AutoFill Destination:=Range(Cells(StartTemp, 9), Cells(EndTemp, 9)), Type:=xlFillDefault
End With

现在试试吧。

【讨论】:

  • +1 很好的解释 Sidd 一如既往。 @JasonR,您也可以摆脱自动填充:With Range(Cells(StartTemp, 9), Cells(EndTemp, 9)) .Formula = "=RC[-6]/(RC[-6]+RC[-5]) * 100" .NumberFormat = "0.00%" End With
  • 谢谢山姆。 :) 我记得你上次也建议过这个。这一次,它跳过了我的脑海。现在每次看到自动填充,我都会想起你:)
  • 太棒了,感谢大家的意见。我已经进行了调整,现在对我来说效果很好。再次感谢!
  • @JasonR:请记住通过选择相关帖子作为答案来结束问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
相关资源
最近更新 更多