excel vba count number of blank cells below each non empty cells

大憨熊 提交于 2020-07-10 07:59:50

问题


I am quite new with Excel VBA. What I want to do is create a VBA loop that will count the number of cells below each non empty cells.

col c   col d
abc     1
        2
        3
        4
abc     5
        6
        7
        8
        9
        10

Here's what I've tried so far:

Sub test()

Dim a, b, c, d, i, k As Integer
Dim y As Range

k = Worksheets("Sheet2").Range("d" & Rows.Count).End(xlUp).Row '13
a = 3
b = 3

For i = 4 To k                        
    If IsEmpty(Cells(i, 3)) = True Then        
        c = c + 1                    
    Else        
        d = d + 1            
    End If    
Next

MsgBox c
MsgBox d

End Sub

回答1:


try this

Sub main2()
    Dim iArea As Long
    Dim rng As Range

    With Worksheets("Sheet2")
        Set rng = .Range("D4", .Cells(.Rows.count, "D").End(xlUp)).Offset(, -1) '<--| set the range of its column "C" cells corresponding to its column "D" ones from row 2 down to last not empty one
        With rng.SpecialCells(xlCellTypeConstants) '<--| reference not empty rng cells
            For iArea = 1 To .Areas.count - 1
                MsgBox .Parent.Range(.Areas(iArea).Cells(1, 1), .Areas(iArea + 1).Cells(1, 1).Offset(-1)).SpecialCells(xlCellTypeBlanks).count
            Next iArea
            MsgBox .Parent.Range(.Areas(iArea).Cells(1, 1), rng(rng.Rows.count)).SpecialCells(xlCellTypeBlanks).count
        End With
    End With
End Sub


来源:https://stackoverflow.com/questions/40945455/excel-vba-count-number-of-blank-cells-below-each-non-empty-cells

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!