简体   繁体   中英

Select a range based on text value in a cell when recording a Macro

I have a csv file I have recorded a macro for to manipulate the data of the CSV file as I need it. Part of the macro looks for a cell containing the text "month index". Once this cell is located, a range is selected (A9,B50) for example. The problem is, the "month index" cell can be located in A7, A8, A11 etc so the macro pulls the wrong data if the cell reference is difference. The range I select is consistent once "month index" is found so I think I can use the offset instruction in someway but not sure.

Currently my Macro that handles this bit looks like this:

        Range("A1").Select     
        Cells.Find(What:="month index", After:=ActiveCell, LookIn:=xlFormulas, _    
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _        

MatchCase:=False, SearchFormat:=False).Activate     
        Range("A9:B9").Select     
        Range(Selection, Selection.End(xlDown)).Select     
        Selection.Cut 
  • Can anyone help me figure this out?

Using the Macro Recorder is great to get started on a task, however it adds a ton of extra code that is inefficient. Learn how to Avoid Select/Activate .

You need to grab the row that 'Month index" appears in, since it is dynamic and moves, you can't just select the same range all the time, it needs to move based on the row found...try something along these lines.

Dim iRow as Integer, iMax as Integer

iRow = Cells.Find(What:="month index", After:=ActiveCell, LookIn:=xlFormulas, _    
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _        
    MatchCase:=False, SearchFormat:=False).Row

iMax = Cells(iRow, "A").End(XlDown).Row
Range("A" & iRow & ":B" & iMax).Cut 

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