简体   繁体   中英

How to copy data from one sheet using column name and paste to another sheet with same column name?

I want to copy data from one Excel sheet by using "column name" and paste that data to another sheet with same column name using VBA. I am using Excel 2016.

I don't want to use column letter as reference while copying data. I want to use column name, since my sheet keeps changing.

This function takes as parameters the sheet in which you're searching for the column name and the column name you're searching for. It returns zero, if you enter an invalid name:

 Function FindColumnName(rng As Range, colName As String) As Long

    On Error Resume Next
    FindColumnName = rng.Find(What:=colName, _
        Lookat:=xlWhole, _
        LookIn:=xlValues, _
        SearchOrder:=xlByColumns, _
        MatchCase:=True).Column
End Function

For instance, if the column name "Test" is present in row one of column G, invoke the function like this

FindColumnName(ActiveSheet.Rows(1), "Test") ' change sheet name as required

and it will return "7".

With regards to the copy-paste part of your question, simply record a macro and go from there.

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