Consulting

Results 1 to 4 of 4

Thread: Simple question...

  1. #1

    Simple question...

    What does the 'Count' function do in vba? For example; Dim Count As Integer OR Count + 1

  2. #2
    VBAX Regular
    Joined
    Feb 2011
    Posts
    13
    Location
    Quote Originally Posted by JLSHARP92
    What does the 'Count' function do in vba? For example; Dim Count As Integer OR Count + 1
    The code you've posted doesn't use Count as a function, but as a variable.

  3. #3
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    In VBA, the same "thing" can have different uses.
    From VBA Help
    Count Property
    Returns the number of objects in a collection.
    as in
    [VBA]Sub Test1()
    Dim rng As Range
    Set rng = Range("A1:A1003")
    MsgBox rng.Cells.Count
    End Sub
    [/VBA]

    However, Properties can also be used as variable names as in

    [VBA]Sub Test2()
    Dim Count As Integer
    Dim i As Integer
    For i = 1 To 100
    Count = Count + i
    Next
    MsgBox Count
    End Sub[/VBA]

    It is good practice not to use a Property as a Variable name to avoid confusion. Your code may work, but will be harder to comprehend.

    [VBA]Sub Test3()
    Dim rng As Range
    Dim Count As Integer
    Dim i As Integer

    For i = 1 To 100
    Count = Count + i
    Next

    Set rng = Range("A1:A" & Count)
    MsgBox Count & vbCr & rng.Cells.Count

    End Sub
    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  4. #4
    Quote Originally Posted by mdmackillop
    In VBA, the same "thing" can have different uses.
    From VBA Help

    as in
    [VBA]Sub Test1()
    Dim rng As Range
    Set rng = Range("A1:A1003")
    MsgBox rng.Cells.Count
    End Sub
    [/VBA]

    However, Properties can also be used as variable names as in

    [VBA]Sub Test2()
    Dim Count As Integer
    Dim i As Integer
    For i = 1 To 100
    Count = Count + i
    Next
    MsgBox Count
    End Sub[/VBA]

    It is good practice not to use a Property as a Variable name to avoid confusion. Your code may work, but will be harder to comprehend.

    [VBA]Sub Test3()
    Dim rng As Range
    Dim Count As Integer
    Dim i As Integer

    For i = 1 To 100
    Count = Count + i
    Next

    Set rng = Range("A1:A" & Count)
    MsgBox Count & vbCr & rng.Cells.Count

    End Sub
    [/VBA]
    Thank you very much for this.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •