2016-03-03 266 views

回答

2

試試這個:

Range(WB.Sheets(1).Cells(2, X), _ 
WB.Sheets(1).Cells(2, Y)).Cells.SpecialCells(xlCellTypeConstants).count 

您應該在單元格之前而不是範圍之前添加工作簿和工作表

+0

備受讚賞! –

1

嘗試了這種方式:

Dim nonBlanck as long 
    nonBlanck = WorksheetFunction.CountA(WB.Sheets(1). _ 
       Range(Cells(2, X), Cells(2, Y)). _ 
         SpecialCells(xlCellTypeConstants)) 

但是,如果WB.SHeets(1)不活躍,那麼你可能有一些問題。因此這種改進方案嘗試:

Dim nonBlanck as long 
    With WB.Sheets(1) 
     nonBlanck = WorksheetFunction.CountA(_ 
       .Range(.Cells(2, X), .Cells(2, Y)). _ 
         SpecialCells(xlCellTypeConstants)) 
    End With 
2

因爲你可能知道你可以做到這一點使用Excel公式​​。

您可以在VBA中使用也使用這樣的:

with WB.sheets(1) 
    WorksheetFunction.CountA(Range(.Cells(2, X), .Cells(2, Y))) 
end with 
1

您需要一種方法來定義修剪列的範圍,然後應用SpecialCells

Sub dural() 
    Dim x As Long, y As Long, rng As Range 

    x = 3 
    y = 5 
    Set rng = Range(Cells(2, x), Cells(Rows.Count, y)) 
    MsgBox rng.Cells.SpecialCells(xlCellTypeConstants).Count 
End Sub 

enter image description here