Copy data from one excel sheet to another (complex) using VBA based on column name

前端 未结 3 428
北恋
北恋 2021-01-07 11:24

I\'m very new to VBA and after 5 hours of watching videos and Googling, I think this is just too over my head... any help is very much appreciated.

So I have 2 excel

3条回答
  •  一整个雨季
    2021-01-07 12:12

    When researching this further I was looking into creating a static array for the headers... then user3561813 provided this gem (I altered it slightly for my if statement and to loop through the sheet:

    Sub validatetickets()
    
    Do Until ActiveCell.Value = ""
    If Cells(ActiveCell.Row, 43) = "Y" Then
    
    Dim wsOrigin As Worksheet
    Dim wsDest As Worksheet
    Dim nCopyRow As Long
    Dim nPasteRow As Long
    Dim rngFnd As Range
    Dim rngDestSearch As Range
    Dim cel As Range
    
    Const ORIGIN_ROW_HEADERS = 1
    Const DEST_ROW_HEADERS = 1
    
    
    Set wsOrigin = Sheets("Case")
    Set wsDest = Sheets("Sheet1")
    
    nCopyRow = ActiveCell.Row
    nPasteRow = wsDest.Cells(Rows.Count, 1).End(xlUp).Row + 1
    
    Set rngDestSearch = Intersect(wsDest.UsedRange, wsDest.Rows(DEST_ROW_HEADERS))
    
    For Each cel In Intersect(wsOrigin.UsedRange, wsOrigin.Rows(ORIGIN_ROW_HEADERS))
    On Error Resume Next
        Set rngFnd = rngDestSearch.Find(cel.Value)
    
        If rngFnd Is Nothing Then
            'Do Nothing as Header Does not Exist
        Else
            wsDest.Cells(nPasteRow, rngFnd.Column).Value = wsOrigin.Cells(nCopyRow, cel.Column).Value
        End If
    On Error GoTo 0
    
    Set rngFnd = Nothing
    Next cel
    ActiveCell.Offset(1, 0).Select
    Else: ActiveCell.Offset(1, 0).Select
    End If
    
    Loop
    End Sub
    

    This is pretty slick the way it works and is very scalable. Doesn't depend on both sheets having identical columns etc... I can see this being very useful in the future. :)

提交回复
热议问题