根据列名称提取数据

时间:2019-09-01 14:02:46

标签: excel vba

获取标题名称的列值时遇到麻烦。我试图在线搜索,但找不到任何解决方案。需要使用列值将数据从一张纸复制到另一张纸。

非常感谢您的帮助

Sub CopyCols()

    Dim h As Range, f As Range, sht1, rngDest As Range
    Dim ColNum As Integer
    Dim lastRow As Long

    Set sht1 = ThisWorkbook.Sheets("Data")
    Set rngDest = ThisWorkbook.Sheets("DataDb").Range("A1") 'start pasting here

    'loop through the headers to copy
    For Each h In sht1.Range("N1:AJ1").Cells
    'find the header on sheet1
    Set f = sht1.Rows(4).Find(what:=h, lookat:=xlPart)
    ColNum = f.Column
        If Not f Is Nothing Then
            'found the header: copy the column
            lastRow = sht1.Cells(Rows.Count, ColNum).End(xlUp).Row
            Sheet2.Range(Cells(4, ColNum), Cells(lastRow, ColNum)).Copy
            rngDest.PasteSpecial Paste:=xlValues, _
            Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            Application.CutCopyMode = False
        End If
        Set f = Nothing
    Next h
End Sub

0 个答案:

没有答案