Forum Discussion
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
ActiveCell.Offset(1, 0).select
Loop
But we are no longer allowed to use ".select" and have to keep the cursor at a cell that isn't lined up with the data.
I have tried to figure a way to nest so I can use variables as such:
For i = 1 To 500
Do While ActiveCell.Value <> ""
n = n + 1
ActiveCell.Offset(i + 5, -15)
Loop
Next i
but not sure how to move it down each time without actually doing so. The "500" is just a generic large number. the actual count is around 350 or so which i am looking to make n be.
Thanks ahead for any help.
2 Replies
- Matt MickleBronze Contributor
Christopher-
Just wanted to follow up and see if you were able to resolve your issue and check in and see how the VBA class was coming along? Feel free to post any VBA questions to the community if you're having any trouble or need a helping hand.
- Matt MickleBronze 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