简体   繁体   中英

create range with find and lastrow

This is killing me. I want to find a cell containing, for example, word "alex" in the first column. Let's call this cell cell-alex.

The idea is to make: range(cell-alex, cells(lastrow, 1)).

I know how to get to the lastrow, but the cell-alex is killing me (I don't think excel can see it. It always selects the range from A1 to the lastrow).

Here is a piece of code:

Cells.Find(What:="alex", after:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True _
            , SearchFormat:=True).Select        
    Set sht = Worksheets(sheetbr)
    lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
    Range(ActiveCell, Cells(lastrow, 13)).Select

if you know for sure that "Alex" is in column 1, then use this:

With Worksheets(sheetbr)
    .Range(.Columns(1).Find(What:="alex", after:=.Cells(.Rows.Count, 1), LookIn:=xlFormulas, LookAt:=xlPart, _
                            SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True, _
                            SearchFormat:=True), _
           .Cells(.Rows.Count, "A").End(xlUp)).Select
End With

otherwise use this:

Dim f As Range

With Worksheets(sheetbr)
    Set f = .Columns(1).Find(What:="alex", after:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True _
            , SearchFormat:=True)
    If Not f Is Nothing Then .Range(f, .Cells(.Rows.Count, "A").End(xlUp)).Select
End With

I think the problem is LookIn:=xlFormulas. Try changing to LookIn:=xlValues

All right, I have figured out this. I did not tell you everything. I start my code with importing another document. While I was working on my code, the moment you mention ActiveCell it starts working with the other book. I resolved it by copying data from my imported spreadsheet to the original (book1). The rest was easy. Here it goes:

Set sht = ThisWorkbook.Worksheets(1)
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'to find the lastRow
Cells.Find(What:="GuV 7", after:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
            , SearchFormat:=True).Activate
Range(ActiveCell, Cells(lastrow, 13)).Select 'I need columns 1-13

Once again, thanks guys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM