countif输出“true”或“false”而不是数字vba

我一直在试图编写一个countif函数到一个循环中,但是,我对输出有一些问题。 当计算发生时,不是读取一个数字,而是继续输出“真”或“假”。 也许在我的代码中有一个错误,但是我在过去已经使用了许多countif函数,而没有遇到像这样的问题。 正如你在下面看到的,我试图用两种不同的方式来写这个函数,但是都没有工作或输出“真”或“假”。

请帮忙。

Sub CorrectSets() Dim Cell As Range Range("B100000").End(xlUp).Select LastRow = ActiveCell.Row For Each Cell In Range("S2:S" & LastRow) StartTime = Cell.Offset(0, -12) Shift = Cell.Offset(0, -14) SortedOp = Cell.Offset(0, -17) DOW = Cell.Offset(0, -5) 'Cell.Value = CountIF(E2:E & LastRow, Shift, N2:N & LastRow ,DOW, B2:B & LastRow,SortedOp, G2:G & LastRow, " < " & StartTime) Cell.Value = "=CountIF(E2:E" & LastRow & ", " & Shift & ", N2:N" & LastRow & "," & DOW & ", B2:B" & LastRow & "," & SortedOp & ", G2:G" & LastRow & ", " < " " & StartTime & ")" Next Cell 

如果你想在单元格中joincountif() 公式 ,那么:

 Cell.Formula = "=CountIF(E2:E &............... 

如果你想把公式的结果放在Cell中,那么:

 Cell.Value = Application.Worksheetfunction.CountIF(E2:E &.................... 

你应该使用

 Cell.Formula = "=CountIFs..." 

要么

 Cell.Value = WorksheetFunction.CountIfs... 

见官方文档 。

加:

  1. 要查找列中包含数据的最后一行(本例中为B),请使用

     Dim ws as Worksheet Set ws = ActiveSheet Dim LastRow as Long LastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row 

    ws是对感兴趣的工作表的引用(在我的例子中是ActiveSheet )。 看到这个答案 。

  2. 你宁愿完全限定你的范围,并避免使用Select除非它是严格需要的。 通过上面的代码,

     Range("B100000").End(xlUp).Select 

    可能不需要。

  3. 如果使用Cell.Formula = "=CountIFs..." ,可能会方便使用

     Dim frm as String frm = "=CountIFs..." Cell.Formula = frm 

    以便于debugging。