通过vba分配单元格公式时的运行时错误1004

时间:2012-07-05 18:49:29

标签: excel-vba excel-2007 excel-formula vba excel

从代码中,根据特定条件,我试图将公式分配给特定单元格。见代码

        For l = 8 To lEND
        lPriorNum = .Range("N" & l)
        If lPriorNum = 1 Then
            sFormula = "=ROUND(IF(AND(N" & l & "=1,K" & l & "=0),O" & l & _
            "/100*M" & l & ",(IF(AND(N" & l & "=1,K" & l & "<>0,K" & l & _
            "<M" & l & "),K" & l & ",M" & l & "))),2)"
        Else
            sFormula = "=ROUND(IF(P" & l & "=0,0,(IF(AND(N" & l + 1 & _
            "<>1,K" & l + 1 & "<>0,M" & l + 1 & ">R" & l + 1 & _
            "),K" & l + 1 & ",(IF(AND(N" & l + 1 & "<>1,K" & l + 1 & _
            "<>0,P" & l & ">0,P" & l & "<K" & l + 1 & "),+P" & l & _
            ",(IF(AND(N" & l + 1 & "<>1,K" & l + 1 & "=0,P" & l & _
            "<=0),0,(IF(O" & l + 1 & "/100*SUM(M" & l + 1 & "-L" & l & _
            ")>M" & l + 1 & ",0,(IF(O" & l + 1 & "/100*SUM(M" & l + 1 & _
            "-R" & l & ")<M" & l + 1 & ",O" & l + 1 & "/100*SUM(M" & l + 1 & _
            "-R" & l & "),(IF(M" & l + 1 & "<=R" & l + 1 & ",IF(P" & l + 1 & _
            "-K" & l + 1 & "<0,0,+M" & l + 1 & "-K" & l + 1 & ")))))))))))))),2)"
        End If            
        .Range("L" & l).Select
        Selection.NumberFormat = "0.00"
        ActiveCell.Formula = sFormula
        Selection.NumberFormat = "0.00"
        ' Total Payout Available
        sFormula = Range("Tot_Pay_Avail").Formula
        .Range("P" & l).Select
        Selection.NumberFormat = "0.00"
        ActiveCell.Formula = sFormula
        Selection.NumberFormat = "0.00"
        ' Final Dist Running Bal
        sFormula = Range("Final_Dist_RB").Formula
        .Range("Q" & l).Select
        Selection.NumberFormat = "0.00"
        ActiveCell.Formula = sFormula
        Selection.NumberFormat = "0.00"
        sFormula = Range("Payout_Amt_Sum").Formula
        .Range("R" & l).Select
        Selection.NumberFormat = "0.00"
        ActiveCell.Formula = sFormula
        Selection.NumberFormat = "0.00"

        sFormula = vbNullString
    Next l

当lPriorNum = 1时,填充L的代码可以正常工作。当lPriorNum不是1时,以下是sFormula中的公式,这不起作用。我收到了1004错误:

= ROUND(IF(P9 = 0,0,(IF(AND(N10&LT;大于1,K10&LT;大于0,M10&GT; R10),K10,(IF(AND(N10&LT;大于1,K10&LT ;大于0,P9大于0,P91,K10 = 0,P9&LT; = 0),0,(IF(O10 / 100 * SUM(M10-L9)&GT; M10,0,(IF(O10 / 100 * SUM (M10-R9)

我被告知这个公式,因为它的编写只适用于Excel 2010,我在2007年测试,但是,2010用户在测试时会遇到同样的错误。这个公式或语法写法的问题可能是什么?电子表格中的单元格格式为数字,没有逗号和2位小数。我已经查看了这里和其他网站的一些帖子,但我认为我的问题可能比我在其他帖子中找到的更具体......

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:1)

您需要在2007版本中创建新工作簿。将公式=ROUND(IF(P9=0,0,(IF(AND(N10<>1,K10<>0,M10>R10),K10,(IF(AND(N10<>1,K10<>0,P9>0,P9<K10),+P9,(IF(AND(N10<>1,K10=0,P9<=0),0,(IF(O10/100*SUM(M10-L9)>M10,0,(IF(O10/100*SUM(M10-R9)<M10,O10/100*SUM(M10-R9),(IF(M10<=R10,IF(P10-K10<0,0,M10-K10)))))))))))))),2)粘贴到excel 2007中可以正常运行。

将相同的公式粘贴到97-2003 .xls文件中会给我太多级别的嵌套错误。请注意,已转换的文件会产生相同的问题