VBA - Count Non Blank Cells Using Cell Reference

試著忘記壹切 提交于 2020-06-16 04:23:30

问题


In VBA, using Excel 2016, I am trying to count the number of non-blank cells for a given range but using only the cell integer reference. I've tried the following:

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

Where X and Y are cell references for the columns. Please assist.


回答1:


Try this:

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

You should add the workbook and worksheet before the cell and not before the range




回答2:


You can do this using the excel formula CountA as you're probably aware.

You can also use this in VBA using:

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



回答3:


try in this way:

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

However, if WB.SHeets(1) is not active then you could have some problems. Therefore try with this improved solution:

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



回答4:


You need a way to define the range of clipped columns and then apply 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



来源:https://stackoverflow.com/questions/35770856/vba-count-non-blank-cells-using-cell-reference

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