vba count columns in range code example

Example 1: excel vba can a vba function return a range?

'VBA functions can return an Excel range, but since a range
'is an object, the 'Set' keyword is required:

Function Test() As Range
    Set Test = [A1:Z99]
End Function

Example 2: count number of cell ina range vba

Sub DisplayColumnCount() 
    Dim iAreaCount As Integer 
    Dim i As Integer 
 
    Worksheets("Sheet1").Activate 
    iAreaCount = Selection.Areas.Count 
 
    If iAreaCount <= 1 Then 
        MsgBox "The selection contains " & Selection.Columns.Count & " columns." 
    Else 
        For i = 1 To iAreaCount 
            MsgBox "Area " & i & " of the selection contains " & _ 
            Selection.Areas(i).Columns.Count & " columns." 
        Next i 
    End If 
End Sub

Tags:

Vb Example