Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 基于列名提取数据_Excel_Vba - Fatal编程技术网

Excel 基于列名提取数据

Excel 基于列名提取数据,excel,vba,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

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

非常感谢你的帮助

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

你的代码到底有什么问题?一个数据样本,可以重现您遇到的任何问题,这是有用的。首先,这行Sheet2可能有问题。范围(单元格(4,ColNum),单元格(lastRow,ColNum))。复制放在这里sht1而不是Sheet2。我还可以看到,每个循环都将找到的数据粘贴到循环之前设置的相同位置。另请参见为什么
Sheet2。范围(单元格(4,ColNum),单元格(lastRow,ColNum))。复制
有问题。您需要限定
单元格
所在的工作表
如果不是f,则
为什么要使用双负???@alowflyingpig,以避免使用
转到
来获得循环的下一次迭代。