我的问题是,我想使用countif
函数为VBA排除空白单元格。
大约有65行,但是如果我放置一个范围K2:K1000
,它会计算每个空白单元格,而我只需要计算excel中使用过的单元格。将添加新单元格,因此无需更改任何内容,我需要通过单击命令按钮根据使用的单元格自动放置结果。
我如何通过VBA代码执行此操作?我尝试使用动态范围,但由于某些行的空白单元格,它不起作用。非常感谢您的支持
Sub Button1_Click()
Range("A3") = WorksheetFunction.CountA(Range("K:K"))Range("K9:K1000").Rows.Count
Range("A4") = WorksheetFunction.CountIf(Range("K9:K1000"), "")
End Sub
答案 0 :(得分:2)
这是如何计算第二列(B
)中的非空值:
Sub TestMe()
Range("A3") = WorksheetFunction.CountA(Columns(2))
End Sub
计算空白:
Range("A4") = WorksheetFunction.CountBlank(Columns(2))
答案 1 :(得分:1)
好的,请尝试动态查找K列中的最后一行:
Sub Button1_Click()
Dim lLastRow As Long
' This give you the last used row in column K of the Active Sheet.
lLastRow = Cells(Rows.Count, 11).End(xlUp).Row
' This is the same function you were using.
Range("A3") = WorksheetFunction.CountIf(Range("K9:K" & lLastRow), "<>")
Range("A4") = WorksheetFunction.CountIf(Range("K9:K" & lLastRow), "")
End Sub
答案 2 :(得分:1)
如果你想要检查一个静态范围(或者像某些人已经建议的那样用.end(xlUp)创建动态范围),这个功能应该可以正常工作。
Public Sub CountPopulatedCells()
Dim wb As Workbook
Dim ws As Worksheet
Dim lrow As Long
Dim checkRng As Range
Dim outputRng As Range
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1)
Set outputRng = ws.Range("C3")
'Finds the last populated row in given column
lrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
'Creates a range using the previously created "lrow"
Set checkRng = ws.Range("A2:A" & lrow)
'Calls the function and feeds it "myRng" and puts the result in "outputRng"
outputRng.Value = CountNonBlanks(checkRng)
End Sub
Public Function CountNonBlanks(rng As Range) As Integer
Dim cell As Range
'Zeros the ingteger before counting
CountNonBlanks = 0
'Checks each cell in range given (in this case "rng")
For Each cell In rng
'Checks if the cell is empty or not
If Not IsEmpty(cell) Then
'Adds 1 to the output integer for each non-empty cell
CountNonBlanks = CountNonBlanks + 1
End If
Next
End Function
我发现使用xlCellTypeConstants和WorksheetFunction有时会引发奇怪的错误。我确定他们为什么这么做(这可能是我的错),但我从来没有遇到任何问题。
此函数将遍历指定范围内的每个单元格,并将值1添加到函数输出整数。每次运行宏时,整数都会自动归零。
编辑1:我之所以选择注入&#34; rng&#34;进入函数而不是在函数本身内创建函数是为了让你可以在整个主子函数中使用它与几个不同的范围。Edit2:我添加了可以调用该函数的sub本身,以及对每个部分所做的一些评论。
答案 3 :(得分:0)
如果你想知道列K中有多少空单元格而不是你的使用范围,那么这样就可以了:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
Dim Lastrow As Long, useRange As Long
Lastrow = ws.Cells(ws.Rows.Count, "K").End(xlUp).Row
'get the last row with data on Column K
useRange = ws.UsedRange.Rows.Count
'get the last row with data on your UsedRange
MsgBox "Your ratio of empty cells in Column K is: " & Lastrow & "/" & useRange
End Sub
答案 4 :(得分:0)
尝试使用它。
Sub Button1_Click()
Range("A3") = Worksheets("Sheet1").Columns(11).SpecialCells(xlCellTypeConstants).Count
Range("A4") = Worksheets("Sheet1").Columns(11).SpecialCells(xlCellTypeBlanks).Count
End Sub