我在使用countif功能来显示给定单元格中的分数频率时遇到了一些麻烦。这是我正在努力从一组给定的导出数据生成报告的更大宏的一部分。
当我尝试运行代码时,它会返回我指定的单元格中的所有零,即使其中的数据符合我的条件。
如果你想批评这段代码,请随意,因为我刚刚开始编程,并希望尽可能多地学习。
提前致谢!
以下是代码的副本:
Dim i As Integer
Dim ws_raw As Worksheet
Dim ws_rpt As Worksheet
Set ws_raw = Sheets("Raw Data")
Set ws_rpt = Sheets("Report")
If ws_raw.Range("H2") <> "" Then
i = WorksheetFunction.CountIf(Range("S2:CCC2"), "5")
ws_raw.Range("I2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), "6")
ws_raw.Range("J2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), "7")
ws_raw.Range("K2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), "8")
ws_raw.Range("L2").Value = i
Else
End If
答案 0 :(得分:4)
试一试,
i = WorksheetFunction.CountIf(Range("S2:CCC2"), 5)
看起来像数字的文字与数字不同;例如5<>"5"
。
在相关的说明中,明确引用.Parent工作表被广泛认为是最佳做法&#39;。 With ... End With statement不仅可以清理代码,还可以加快代码速度。我也更喜欢使用Excel Application object而不是WorksheetFunction object,因为任何错误都可以返回给变体。
Dim i As Variant
Dim ws_raw As Worksheet, ws_rpt As Worksheet
Set ws_raw = Sheets("Raw Data")
Set ws_rpt = Sheets("Report")
With ws_rpt
If ws_raw.Range("H2") <> "" Then
i = Application.CountIf(.Range("S2:CCC2"), 5)
ws_raw.Range("I2").Value = i
i = Application.CountIf(.Range("S2:CCC2"), 6)
ws_raw.Range("J2").Value = i
i = Application.CountIf(.Range("S2:CCC2"), 7)
ws_raw.Range("K2").Value = i
i = Application.CountIf(.Range("S2:CCC2"), 8)
ws_raw.Range("L2").Value = i
Else
End If
End With
答案 1 :(得分:1)
您将计数转换为文本的数字用双引号括起来 - 试试这个:
i = WorksheetFunction.CountIf(Range("S2:CCC2"), 5)
ws_raw.Range("I2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), 6)
ws_raw.Range("J2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), 7)
ws_raw.Range("K2").Value = i
i = WorksheetFunction.CountIf(Range("S2:CCC2"), 8)
ws_raw.Range("L2").Value = i