简体   繁体   中英

VBA code to search for a row header, and select the entire range beneath that header

I'm VERY new to VBA and i'm trying to automate some of my day to day tasks. One task that I would like to automate requires me to "search" for a specified header, and select that entire column of data. I will then paste that range into a different spreadsheet.

Tamcolumn = Cells.Find(what:="plan_tamaward", after:="a1", searchdirection:=xlPrevious, searchorder:=xlBycolumn, lookat:=xlPart).Column

I've found this little bit of code to be helpful when i'm defining an entire column, the problem is I can't define the column header and define the range below without "selecting" the data - which I know is a big no-no.

I hope this makes sense.

Thanks in advance.

You can incorporate the following approach into your code...

Dim Col As Long, LastRow As Long
Dim Rng As Range
If Application.CountIf(Rows(1), "plan_tamaward*") > 0 Then
    Col = Application.Match("plan_tamaward*", Rows(1), 0)
    LastRow = Cells(Rows.Count, Col).End(xlUp).Row
    Set Rng = Range(Cells(2, Col), Cells(LastRow, Col))
End If
If Not Rng Is Nothing Then
    MsgBox Rng.Address
    'do whatever you want to do with this range here
Else
    MsgBox "The column named like plan_tamaward* was not found in Row1.", vbExclamation, "Column Not Found!"
    Exit Sub
End If

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