计算非空白单元格结果,而不在Excel VBA中循环 – 例如,使用Specialcells

这里是我想要在VBA中计算的代码,希望从“FormulaResultCount”返回一个“3”计数返回variables。 为什么我不能计算每个单元格内由公式显式返回的内容; 从灰色框(见下面的照片)?

Sub countNonBlanks() Worksheets("Sheet1").Select Range("C:C").Select FormulaResultCount = Selection.SpecialCells(xlCellTypeFormulas).Count 'SpecialCells options from MSFT ' xlCellTypeAllFormatConditions. Cells of any format -4172 ' xlCellTypeAllValidation. Cells having validation criteria -4174 ' xlCellTypeBlanks. Empty cells 4 ' xlCellTypeComments. Cells containing notes -4144 ' xlCellTypeConstants. Cells containing constants 2 ' xlCellTypeFormulas. Cells containing formulas -4123 ' xlCellTypeLastCell. The last cell in the used range 11 ' xlCellTypeSameFormatConditions. Cells having the same format -4173 ' xlCellTypeSameValidation. Cells having the same validation -4175 ' xlCellTypeVisible. All visible cells ' End Sub 

看公式作为参考:

在这里输入图像说明

注意:因为dynamic工作时我会有更多的单元格,循环可能会减慢过程的速度。 另外,我尝试使用CountA没有结果。

xlCellTypeFormulas。 包含公式-4123的单元格

这不会返回基于它们的值的单元格,但如果他们有任何公式或不。 根据你的工作表,你应该得到5

另外,请不要使用。请selectINTERESTING READ

你的代码也可以写成

FormulaResultCount = Worksheets("Sheet1").Columns(3).SpecialCells(xlCellTypeFormulas).Count

另一个提示 :使用SpecialCells ,请使用适当的error handling,以便如果没有与SpecialCells条件匹配的单元格,您的代码将不会中断。 看到这个例子。

 Sub Sample() Dim ws As Worksheet Dim Rng As Range Set ws = ThisWorkbook.Sheets("Sheet1") With ws On Error Resume Next Set Rng = .Columns(3).SpecialCells(xlCellTypeFormulas) If Err <> 0 Then MsgBox "No Cells with formulas were found" Exit Sub End If On Error GoTo 0 End With FormulaResultCount = Rng.Count Debug.Print FormulaResultCount End Sub 

跟随从评论

 Sub Sample() Dim ws As Worksheet Dim lRow As Long Set ws = ThisWorkbook.Sheets("Sheet1") With ws lRow = .Range("A" & .Rows.Count).End(xlUp).Row Debug.Print Evaluate("=COUNTA(C1:C" & lRow & _ ")-COUNTIF(C1:C" & lRow & ","""")") End With End Sub 

你真正想要的是:

 FormulaResultCount = Evaluate("CountA(C:C)") 

我刚刚了解了评估命令。 这很棒!

它给你3 🙂

也许这个:

 FormulaResultCount = WorksheetFunction.CountIf(Range("C:C"), "?*") 

因此,计算以任何字符开始的范围内的所有单元格?

您可以在不使用VBA的情况下使用公式。

 =ROWS(range)*COLUMNS(range)-COUNTBLANK(range) 

如果你想在VBA中做到这一点,你可以使用这个:

 Function non_blank_cell_results_count(r As Range) As Long non_blank_cell_results_count = r.Cells.Count - WorksheetFunction.CountBlank(r) End Function