简体   繁体   中英

Paste cells in specific row based on column header

I am not a programmer but would appreciate some help!

I am trying to take a range of cells, and paste them in another part of the spread sheet but in the correct column that I want (the column will change later that's why I want it to identify the column to paste the cells into the right row)

Example, take cells (A2:A10) and paste them into the "TTM" column D4:D12... where I have put the text TTM into D1... later, TTM may become E1, in which case the A2:A10 cells need to be moved to E4:E12...

Thanks a lot!

The following Function can be used to do what you want. You will need to explain what will trigger this code and if you want to search other than the 'Active Sheet'

Function Move_Cells()
Dim iCols   As Integer
Dim i       As Integer
Dim strKey  As String
Dim iNewCol As Integer

    strKey = "TTM"      ' Set this to whatever label you want to search row 1 for.
    iCols = ActiveSheet.UsedRange.Columns.Count         ' Get count of used columns

    For i = 1 To iCols              ' Find column containing 'TTM'
        If LCase(Cells(1, i).text) = LCase(strKey) Then     ' ignore case inCASE SoMeBody....
            iNewCol = i             ' Save col # containing search keyword
            Exit For
        End If
    Next i

    'ActiveSheet.Range("A2:A10").Copy        ' Where to copy from
    'ActiveSheet.Cells(2, iNewCol).PasteSpecial xlPasteValues        ' Paste into new location
    'Application.CutCopyMode = False

    ' Try the following instead of the previous copy/paste
    Range("A2:A10").Select
    Selection.Copy
    Cells(2, iNewCol).Select
    ActiveSheet.Paste

End Function

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