Find the last cell address using vba excel

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

I have searched this site and it seems like all the answers just point to finding the row number of the cell.

I am trying to set a range so that it will go from A1 to the end of the data in the A column. This spreadsheet will be updated weekly so there will be data added to it every week.

I was wondering what code would work so that I can either find the row number and somehow tie it in with my range code so that it will equal "A" + lastrownumber? OR if there is code that will provide the column and row number together? If I have missed the link to the correct answer a simple link will do as well and I apologize for the post and your time.

Here is my code:

Sub NamedRange()  Dim Rng1 As Range Dim newDate As Integer Dim NumberOfRows As Range   Dim MyRange As Range Dim lastRow2 As Range   lastRow2 = Range("A65536").End(xlUp).Row 'lastRow2 = LastRow  Set Rng1 = Sheets("Sheet1").Range(lastRow2) ActiveWorkbook.Names.Add Name:="MyRange", RefersTo:=Rng1   Dim date1 As String Dim dat As Date Dim newPrice As Double   Set RgSales = Range("MyRange") 

回答1:

This will return the range object corresponding to the last filled in cell in column A

Range("A:A").Find("*",Range("A1"),SearchDirection:=xlprevious) 

If you want the row number, use the following:

Range("A:A").Find("*",Range("A1"),SearchDirection:=xlprevious).row 


回答2:

This will give the last row in a given column

= Cells(Activesheet.Rows.Count, ColumnNumber).End(xlUp).Row (Fixed per @Gimp)

you then have a reference you can use to add to the data - e.g if you want to look in column "A", then that would be columnnumber 1. feed that into the function, then you can use Cells(NumberReturnedFromFunction,ColumnNumber) to address that cell, and add .Address if you want the A1 style of address



回答3:

Try using something like this:

Activesheet.Cells(Activesheet.Rows.Count, "A").End(xlUp).Row 

You can replace Activesheet with references to a sheet's index # like Sheets(1) or the sheet name like Sheets("Sheet1")

By using the Rows.Count it will check to see what the max rows are and be compatible across all versions of Excel.

In the end you can use this within your range reference like this:

Msgbox Sheets(1).Range("A" & Sheets(1).Cells(Sheets(1).Rows.Count, "A").End(xlUp).row).value 

But I'd probably rewrite that as

With Sheets(1)     Msgbox .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).row).value End With 


回答4:

In case there are gaps in the data I'd avoid using xlDown so something like the following is fine. Try it in the immediate window:

Activesheet.range("A1:A" & Activesheet.Cells(Excel.Rows.Count, 1).End(Excel.xlUp).Row).select 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!