[英]Runtime error 1004 with Count and Countif formula VBA
I am getting run time error 1004 when converting the following formula to code: 将以下公式转换为代码时,出现运行时错误1004:
When I try to consider the only Count forumlas, it was working. 当我尝试考虑唯一的Count Forumlas时,它正在工作。
Formula: 式:
=(COUNT(C25:C26)-COUNTIF(C25:C26,0))/(COUNT(E25:E26)-COUNTIF(E25:E26,0))
Code: 码:
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 ))"
Don't make it to confusing, 不要把它弄糊涂了,
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))"
Further to my comments, this is how you will qualify your cells object. 除了我的评论,这就是如何限定单元格对象的方式。 Notice the DOT before cells?
注意到细胞之前的DOT吗?
Tested 经测试
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
You forgot some brakets/parenthesis and let spaces . 您忘记了一些措辞/括号,让了空格 。
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
Use a string variable to debug and prompt it with a MsgBox
. 使用字符串变量调试并使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.