计数和Countif公式VBA运行时错误1004

将以下公式转换为代码时,运行时错误1004:

当我试图考虑唯一的计数论坛,它正在工作。

式:

=(COUNT(C25:C26)-COUNTIF(C25:C26,0))/(COUNT(E25:E26)-COUNTIF(E25:E26,0)) 

码:

 Sheets("Sheet1").Cells(29, 3).Formula = "=(COUNT(" & Sheets("Sheet1").Range(Cells(25, 3), Cells(26, 3)).Address(False, False) _ & "- COUNTIF(" & Sheets("Sheet1").Range(Cells(25, 3), Cells(26, 3)).Address(False, False) & ",0 )/" & _ "(COUNT(" & Sheets("Sheet1").Range(Cells(25, 5), Cells(26, 5)).Address(False, False) _ & "- COUNTIF(" & Sheets("Sheet1").Range(Cells(25, 5), Cells(26, 5)).Address(False, False) & ",0 ))" 

忘了一些括号/括号,让空格

 With Sheets("Sheet1") .Cells(29, 3).Formula = _ "=(COUNT(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) _ & ")-COUNTIF(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0))/" & _ "(COUNT(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) _ & ")-COUNTIF(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0))" End With 

使用一个stringvariables进行debugging,并用MsgBox提示。

 Dim StrFormula As String With Sheets("Sheet1") StrFormula = _ "=(COUNT(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) _ & ")-COUNTIF(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0))/" & _ "(COUNT(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) _ & ")-COUNTIF(" & .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0))" End With MsgBox StrFormula 

不要混淆,

 Range("C29") = _ "=(COUNT(Sheet1!R[-4]C:R[-3]C)-COUNTIF(Sheet1!R[-4]C:R[-3]C,0))/(COUNT(Sheet1!R[-4]C[2]:R[-3]C[2])-COUNTIF(Sheet1!R[-27]C[2]:R[-4]C[2],0))" 'or Range("C29") = _ "=(COUNT(Sheet1!C25:C26)-COUNTIF(Sheet1!C25:C26,0))/(COUNT(Sheet1!E25:E26)-COUNTIF(Sheet1!E2:E25,0))" 

除了我的评论,这是你将如何限定你的细胞对象。 注意细胞之前的DOT?

经testing

 Sub Sample() Dim ws As Worksheet Dim sFormula As String Set ws = ThisWorkbook.Sheets("Sheet1") With ws sFormula = "=(COUNT(" & _ .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ")" & _ "- COUNTIF(" & _ .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0 ))/" & _ "(COUNT(" & _ .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ")" & _ "- COUNTIF(" & _ .Range(.Cells(25, 3), .Cells(26, 3)).Address(False, False) & ",0 ))" Debug.Print sFormula .Cells(29, 3).Formula = sFormula End With End Sub