2016-12-03 290 views
0

我对Excel VBA很新颖。我想要做的是创建一个VBA循环,它将计算每个非空单元下的单元数。excel vba count每个非空单元格下面的空白单元格的数量

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

这里是我试过到目前为止:

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 
+0

你的问题不明确。你的预期产出是多少?用逻辑解释。 – harun24hr

+0

对不起。我想要做的是获得每个非空白行下的空白行数。比如说第一个abc会导致3,那么第二个abc将会导致5 – lsatienz

+0

@lsatienz实际上第二个结果是无穷大(或者非常高),因为C列末尾没有单元格,对吧?代码如何知道最后一个'abc'的停止位置? –

回答

0

试试这个

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 
+0

该死的你快,即使在星期六:)你忘了每个结果的'MsgBox' –

+0

@ShaiRado,你好。我将使用Msgbox选项进行编辑。谢谢 – user3598756

+0

谢谢user3598756很大的帮助。是的。 il做msgbox就可以了 – lsatienz

相关问题