Forum Discussion
Christopher Easton
Apr 03, 2018Copper Contributor
Do loops - without moving cursor
Hi,
S I am in a VBA class, and the teacher wants to count rows and columns with a do loop without moving the cursor.
usually I would use:
Do While ActiveCell.Value <> "" n = n + 1
A...
Matt Mickle
Apr 03, 2018Bronze Contributor
I'm going to try to help you arrive at the answer by yourself by providing examples that are close to what you would like to accomplish but not quite exactly what you need to submit to your teacher. I think the best way to learn is by practice. I taught myself VBA from going on message boards like this and asking questions so I firmly believe this resource is fundamental in developing your VBA skillset. I have provided a few examples below of different ways to get the information that you need using different parts of the VBA object model as well as a For Next Loop. Hopefully these examples can help you arrive at the answer independently.
Sub FindLColAndLRow()
Dim Rng As Range
Set Rng = Sheets("Sheet1").Range("A1").CurrentRegion 'Define Contiguous Data Range based on cell Al
rowCnt = Rng.Rows.Count 'Get Data Row Count
colCount = Rng.Columns.Count 'Get Data ColumnCount
End Sub
Sub FindLrowExample()
Dim Lrow As Long
Dim LCol As Long
Set sht = Sheets("Sheet1") 'Define Worksheet
Lrow = sht.Cells(Rows.Count, "A").End(xlUp).Row 'Get Last Row based on Column A
End Sub
Sub ForNextExample()
Dim sht As Worksheet
Dim Counter As Integer
Set sht = Sheets("Sheet1") 'Define Worksheet
'Increment from 1 to 500
For x = 1 To 500
'Check to identify if a cell has a value
If sht.Cells(x, "A") <> "" Then
Counter = Counter + 1 'Count Rows 1 at a time that meet criteria
End If
Next x
MsgBox Counter
End Sub