Find the last value (not the last row) in a column [duplicate] - excel

This question already has answers here:
lastrow and excel table.
(6 answers)
Closed 6 months ago.
I have a worksheet with a table that is constantly being updated, so the number of rows it has is variable. I am interested in retrieving the last value in column B. However, the tricky part is that not all rows in this column of the table have a value. Sometimes the next cell with an actual value could be just below the previous one, and sometimes there could be many empty spaces in between.
I tried to use the following code to do so:
LastValue = Cells(Rows.Count, "B").End(xlUp).Value
The issue I am experiencing happens in a very specific scenario. If we suppose the last cell with a value in the column is B6, but the last cell of the table corresponding to this column is B10, the value retrieved is empty (the one in B10). What I would need to find is cell B6 and give that value to the variable LastValue. Is there any way to do this? I could only find code examples to find the last row of the entire worksheet, ignoring individual columns.

This code works below based on your worksheet being titled Sheet1 and the table as Table 1.
Sub FindLastRowInExcelTable()
Dim lastrow As Long
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
lastrow = ws.ListObjects("Table1").Range.Columns(2).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End Sub
You can modify Columns(2) to change the column you are looking to count.

Related

Worksheet.UsedRange.Rows.Count returns wrong result

In VB.NET I want to get the used rows so I wrote that:
Dim objWorksheet As Excel.Worksheet = workbook.Sheets(2)
Dim lastRow = objWorksheet.UsedRange.Rows.Count
The number of lastRow is less than used rows. I searched the site and someone suggested:
Dim range As Excel.Range = objWorkSheet.UsedRange
Dim lastRow = range.Rows.Count
This returns less than actual used rows.
The solution is in the image:
I found this question it is an overall understanding of the last used row.
UsedRange.Rows.Count means from the first rows that has data to the last rows that has data, which means you can have empty rows between the first non-empty rows to the last non-empty rows which not affect the result, but if the first row is empty, the result will be one less the actual non-empty row, and if the first two row is empty the result will be two less, so the link question said never use UsedRange.Rows.Count to get the last row.
Try to avoid UsedRange. It can be misleading. For instance, if you fill range A1:B5 and clear the contents of column B, then UsedRange.Columns.Count will return 2 - because Excel remembers cells with formatting and includes them into UsedRange.
UPDATE
To get real last column and row, use following code:
lRealLastRow = _
Cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious).Row
lRealLastColumn = _
Cells.Find("*", Range("A1"), xlFormulas, , xlByColumns, xlPrevious).Column
UPDATE 2
Sometimes it only appears too small. Say we have:
and we run:
Sub aRowsByAnyOtherName1()
Dim N As Long
N = ActiveSheet.UsedRange.Rows.Count
MsgBox N
End Sub
We see:
The reason we get 3 rather than 4 is that the top row of the worksheet is not in UsedRange!
EDIT#1:
If the "top" of the worksheet needs to be included then use:
Sub aRowsByAnyOtherName2()
Dim N As Long, rng As Range
Set rng = ActiveSheet.UsedRange
N = rng.Rows.Count + rng(1).Row - 1
MsgBox N
End Sub
This is a bit of a punt on what you mean by "used" rows. If you have any blank rows at the start of the sheet you will get the wrong last row number but you will get the used range row count.
Try the following with row 1 blank.
Option Explicit
Sub test()
Dim rng As Range
Set rng = ActiveSheet.UsedRange
Debug.Print rng.Rows.Count '2
Debug.Print ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row '3
End Sub
This yields 2 from UsedRange.Rows.Count and 3 from using xlCellTypeLastCell with data as below:
I'm using Excel 2013, and as far as I can see the UsedRange and UsedRange.Count Properties work correctly
In previous versions I can remember noticing that they were unreliable, and I think this may be the reasons of some older posts, eg stackoverflow.com/questions/11169445...
Note that the UsedRange is a Single Rectangular Area bounded by the Top-, Right-, Bottom-, and Left-most
Non-Blank Cells, so that the Last Used Row is thus
ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
Note also that UsedRange INCLUDES all Cells that have Any Content, for example a Border, Interior Coloring or a Comment, not just those with a Value or a Formula
Depending on what you are trying to achieve, using the SpecialCells and Find Methods may be preferable; for example the Last Used Row can also be found using
ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
UsedRange does exactly what it is supposed to do in these scenarios. How many rows of data do you have? If you have a block of data in the center of a worksheet with 3 rows and 4 columns, UsedRange returns 3 rows properly. If your worksheet has empty rows in rows 1:3, for example, you must consciously make note of that. UsedRange is very powerful if you format your workbook properly, and even MORE powerful when it's not formatted like that, because it doesn't care where the table is.
As a best practice, you should always have a single, continuous table of data on a spreadsheet starting in cell A1. If you need a summary formatted a few rows and columns in, that should be a separate sheet. And if you get a worksheet from another source that isn't formatted properly, it's your job to fix that before you analyze it -- delete empty rows and columns in front of the table.

I am trying to simplify and Modify this Code [duplicate]

This question already has answers here:
Finding the Last Row and using it in a formula
(2 answers)
Closed 5 years ago.
I would like this Code to count the number of incidents in a column starting at Cell A3 and then go the last cell in the column without me having to define it.
ActiveCell.FormulaR1C1 = _
"=COUNTIF(Data!R[-2]C[-3]:R[647]C[-3],Data!R[-2]C[-3])"
Still new to VBA and learning.
Here's a simple way to locate the last used cell in column C. There are several variations to finding lastRow, this is just one of them. Add your code accordingly.
Dim LastRow As Long
Dim lastCell As Long
lastCell = Range("C65536").End(xlUp).Cell '<<--for finding last active cell reference
lastRow = Range("C65536").End(xlUp).Row '<<--for finding last row number

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

How to get the row count in EXCEL VBA

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

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