2016-12-03 259 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

相關問題