PDA

View Full Version : Simple question...



JLSHARP92
03-22-2011, 03:06 PM
What does the 'Count' function do in vba? For example; Dim Count As Integer OR Count + 1

draco664
03-22-2011, 03:25 PM
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.

mdmackillop
03-22-2011, 03:25 PM
In VBA, the same "thing" can have different uses.
From VBA Help

Count Property
Returns the number of objects in a collection.

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


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

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

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.

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

JLSHARP92
03-22-2011, 03:45 PM
In VBA, the same "thing" can have different uses.
From VBA Help

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


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

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

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.

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


Thank you very much for this.