How to get the row count in EXCEL VBA - excel

I am developing a dashboard in excel. And I am looking for calculating row count. (How many records are present) ..
Since there are some blank cells I thought to go from bottom to up. I use the following
Range("A1048576").Select
Selection.End(xlUp).Select
After this execution the active cell is at A113 which means the row count is 113.
My question is how to get this number 113 from the active cell?

You can use this:
Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row
lastrow will contain number of last empty row in column A, in your case 113

Here is what I usually use for that:
lastrow = WorksheetFunction.CountA(Columns("A:A"))
This will return the number of non-empty cells in Column "A" which is what I think you're after. Hope this helps.

The best way to get the count of rows/records (in most cases) is to use .UsedRange.Rows.Count. You can assign the return value to a variable like this:
lastRow = Sheets(1).UsedRange.Rows.Count
If you use a function that includes a column (such as column A) as shown in other examples, that will only get you the count of rows in that column, which may or may not be what you're going for. One caveat: if you have formatted rows below your last row with a value then it will return that row number.

If there is a slight chance that the last row of the worksheet is not empty, you should add an IsEmpty() check to #simoco 's solution. Therefore; following is a function that returns the last used row and check if the last row of the worksheet is empty:
Function lastRow(WS As Worksheet, iColumn As String) As Long
If Not IsEmpty(WS.Range(iColumn & WS.Rows.Count)) Then
lastRow = WS.Rows.Count
Else
lastRow = WS.Range(iColumn & WS.Rows.Count).End(xlUp).Row
End If
End Function

Related

Replicating values

Need a little help here.
In the "Data" Tab I want to copy values in column "c2:c1000" and paste in column "a1" of another Tab.
This is what i have so far,
Dim x As Long
Dim lastRow As Long
lastRow = Worksheet("Data").Cells(3, Columns.Count).End(xlUp).Column
For x = 1 To lastRow
If Worksheets("Sheet2").Cells(2, "A") = "" Then
Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Range(1, "A")
Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
Else
Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Cells(2,
Columns.Count).End(xlToLeft).Offset(, 1)
'Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss") --> can't figure how to increment this as this will need to be on the subsequent empty column
End If
Next
End Sub
Your help will be greatly appreciated!
Thank you.
Pasting values first into range A1 and down and then next time to cell B1 and so on, leaves no space for the timestamp to A1, B1 etc. So, I assume that you would like to paste the random values to row 2. So cells A1, B1, ... are left for the timestamp.
Inside the With statements we can refer to properties of the wsAudit so we can replace the "Worksheets("Audit")." reference with just "."
The column.count expression just checks the amount of columns in the worksheet.
The expression .Cells(2, Columns.Count) just points to last cell in the row 2.
The .End(xlToLeft).Column then looks from this column to left and is supposed to find the last not empty cell on this row. It's basically the same idea that in Excel's sheet you would go to cell XDF2 and hit CTRL+Arrow Left from keyboard.
But instead of activating the cell we just want to get the columns index number and then add 1 (the new column) and save it into variable. Now the new column is known.
The expression Range(.Cells(2, newColAudit), .Cells(1000, newColAudit)).Value is really the same as e.g. Range("B2:B1000"), but with this we can use the row and column index numbers instead. This is useful as the column number varies.
And as Samuel pointed out the copy paste operation can be avoided by setting the areas equal.
Dim wsAudit As Worksheet
Dim newColAudit As Long
Set wsAudit = Worksheets("Audit")
With wsAudit
newColAudit = .Cells(2, Columns.Count).End(xlToLeft).Column + 1
Range(.Cells(2, newColAudit), .Cells(1000, newColAudit)).Value = Worksheets("Data").Range("C2:C1000").Value
.Cells(1, newColAudit).Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
End With
Much like your LastRow* variable for your source sheet, create a LastColumn variable for your destination sheet, which will find the last used column the same way you are finding your last used row.
Like so:
Dim LastColumn As Long
LastColumn = Sheets("Audit").Cells(1, Columns.Count).End(xlToLeft).Column
Then use the variable like so:
Destination:= Worksheets("Audit").Cells(1, LastColumn)
It seems that your code contradicts your question too, in your question you explained the data will be written to the Audit sheet in row 1, using the next column each time but your code looks for values in row 2 in your If statement:
If Worksheets("Audit").Cells(2, "A") = "" Then is the same as If Worksheets("Audit").Range("A2") = "" Then.
If you mean to check the first row, change the 2 to 1.
To help improve your codes efficiency:
(Also see the link to 'how to avoid select' in that question):
You can achieve 'copy/paste' without actually using the 'copy' and 'paste' methods by assigning the value of one range to the other, as example, like so:
Worksheets("Audit").Cells(1, LastColumn).Resize(999, 1) = Worksheets("Data").Range("c2:c1000").Value
Note: Change the Resize Property rows to suit the source range (in this case you are wanting to move values from C2:C1000).
*The LastRow variable is a bit confusing, as it is looking for the last used column in row 3.
If it's meant to find a column, consider renaming it to avoid confusion later on in debugging.
If it's meant to find the last row, try like this:
LastRow = Worksheet("Data").Cells(Rows.Count, 1).End(xlUp).Row

How to fo find the last row of a selected range

I would like to find the last row in a range that I have selected so that my code is more dynamic and less likely to break if I exceed the range.
I am unsure of the syntax to use.
Instead of P4201, I would like to select the last row with a value within column P, whatever that may be.
Selection.AutoFill Destination:=Range("P2:P4201")
I am just unsure of the last syntax to select the last row with a value with P. Instead of doing P10000, I would like to make it cleaner.
The below macro counts up to the last filled cell in column P, and selects the full range from P2 until P-end.
Sub Select_Range()
Dim I As String
I = Sheet1.Range("P" & Rows.Count).End(xlUp).Row 'Determine last filled cell and count rows
Sheet1.Range("P2" & ":P" & I).Select 'select full filled range in column P.
End Sub
Let me know if this is what you're looking for.

Adding the last row number to an excel formula in VBA

having a bit of a problem and not sure how possible this is. I'm trying to get the last row number (not count) in a column and then use that number in a formula. The reference would be in the SUMIF(R[5] and R[6] statements. I want to change the R to reflect whatever the last row is.
Here is what I have and while it returns the row number I need I can't figure out how to define or use it in the formula. I'm not sure if this is even the best way to do it.
Any help in the right direction would be greatly appreciated!
Sub test()
Dim lrow As Long
lrow = ActiveSheet.Cells(Rows.count, 2).End(xlUp).Offset(1, 0).Select
Selection.Value = ActiveCell.Row - 1
ActiveCell.FormulaR1C1 = "=if(RC[-6]="""",if(RC[-8]=R[-1]C[-8],R[-1]C,SUMIF(R[5]C[-8]:R[6]C[-8],RC[-8],R[5]C[-11]:R[6]C[-11])),"""")"
End Sub
EDIT:
So the idea is to get the formula to look at the column labeled RD/SFC and anything that matches, for example if in RD/SFC row match 6605 we then add everything in the columns Est FNL sales to the end of the row and same for the $Ret Cost column. Currently trying to do that through the formula and put it in Column O.
Hope that helps explain a little bit more
may this help:
'To get the last row with data in a given column
Public Function lastRowInOneColumn(ByVal ws As Worksheet, ByVal givenCol As Long) As Long
With ws
lastRowInOneColumn = .Cells(.Rows.count, givenCol).End(xlUp).Row
End With
End Function

Excel VBA set print area to last row with data

I have an Excel table with a sheet "CR" where columns A to K are filled, with the first row being a header row.
Rows 1-1000 are formatted (borders) and column A contains a formula to autonumber the rows when data in column F is entered.
Sheet "CR" is protected to prevent users from entering data in column A (locked).
Using the Workbook_BeforePrint function, I'm trying to set the print area to columns A to K and to the last row of column A that contains a number.
My code (in object 'ThisWorkbook') is as follows:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Sheets("CR")
' find the last row with data in column A
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
ws.PageSetup.PrintArea = ws.Range("A1:K" & lastRow).Address
End Sub
However, when I click File -> Print, the range of columns A to K up to row 1000 is displayed instead of only the rows that have a number in column A. What am I doing wrong?
Change:
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
To:
lastRow = [LOOKUP(2,1/(A1:A65536<>""),ROW(A1:A65536))]
.End(...) will act like ctrl + arrow-key. if the cell has a formula (which looks empty due to the formula, then it will still stop there... another way would be the use of evaluate (if you do not want to loop) like this:
lastRow = .Evaluate("MAX(IFERROR(MATCH(1E+100,A:A,1),0),IFERROR(MATCH(""zzz"",A:A,1),0))")
This will give the last row (which has a value in column A).
Also check if there are hidden values (looking empty due number format or having characters you can't see directly. Try to go below row 1000 in column A (select a cell after A1000 in column A) and hit ctrl+up to validate where it stops (and why).
EDIT:
(regarding your comment)
"" still leads to a "stop" for the .End(...)-command. So either use my formula, translate the formula into vba or loop the cells it get the last value. Also Find is a good tool (if not doing it over and over for countless times).
lastRow = .Cells.Find("*", .Range("B1"), xlValues, , xlByColumns, xlPrevious).Row

Copy last row in a column in Excel with VBA

I would like to copy the value of the last row in a specific Column in to another cell,
for example this is the code which I a suing to find which is the last used rown in the column G
Dim LastRow As Long
LastRow = Range("G65536").End(xlUp).Row
Right now LastRow get's the value of the address of the row, I need this code modified this way so it will copy the Value of the LastRow (not the address) and than past this value of this cell in to another Cell with address "Q1"
If anywone can Help let me know, thanks!
According to Microsoft MVP:
You should not use numbers because different versions of Excel have different number of maximum rows.
.Cells(.Rows.Count, "Q") is the very last cell at the bottom of column Q.
.Cells(.Rows.Count, "Q").End(xlUp).Row is the row number of the last non-blank cell in column Q.
So you should use
Cells(Rows.Count, "G").End(xlUp).Row
To find number of rows used:
ActiveSheet.UsedRange.Rows.Count
Range.Copy method has parameter which allows you to copy Range into required destination.
According to MSDN Range.Copy syntax looks as follows:
expression.Copy(Destination)
expression A variable that represents a Range object.
In your situation you can call it as follows:
Range("G65536").End(xlUp).Copy Range("Q1")
Where Range("Q1") should be changed to any other cell if required

Resources