2012-04-10 42 views
2

我想动态地设置在我的宏执行时输入公式的单元格。这段代码将循环大约10次,每次都有一部分员工。按部门排序。所以当循环回到这一点时,第一个单元格将会改变。1004错误 - 动态分配公式到一个单元格范围

我得到这个错误:

Method 'Range' of object '_Global' failed

这里是我的代码:

'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 

提前感谢!

+1

哪一行会抛出错误? – RBarryYoung 2012-04-10 19:39:02

+1

什么是错误信息的文本? (1004至少有两个不同的)。 – RBarryYoung 2012-04-10 19:42:42

回答

4

由于你正在使用Range(Cells(StartTemp, 9))

当使用RangeCells你不能只使用一个单元收到这个错误。语法是

范围(小区1,小区2)

enter image description here

这会给你,你得到:)

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

enter image description here

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

更改您的代码这一点,并再次尝试(UNTESTED

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 

现在尝试它。

+2

+1好的解释西德一如既往。 @JasonR,你也可以去除自动填充:'带范围(单元格(StartTemp,9),单元格(EndTemp,9)) .Formula =“= RC [-6] /(RC [-6] + RC [-5])* 100“ .NumberFormat =”0.00%“ End With' – Reafidy 2012-04-10 20:35:24

+1

谢谢Sam。 :)我记得你最后一次提出这个建议。这次它跳过了我的脑海。现在,每当我看到一个自动填充,我会想起你:) – 2012-04-11 00:00:09

+0

真棒,感谢大家的输入。现在我已经为我做了调整和工作。再次感谢! – JasonR 2012-04-11 15:27:40

相关问题