Excel VBA For-Next Loop to extract data from one WB to another

前端 未结 1 369
长发绾君心
长发绾君心 2021-01-26 19:05

I am working on a for loop that extracts entire rows of data based on the string in the 12th column being equal to \"Airfare.\"

The idea is to copy the rows of data wher

1条回答
  •  隐瞒了意图╮
    2021-01-26 19:42

    I would suggest an alternative to looping through each row. Loops are very inefficient and should be avoided if possible.

    Assuming your data is stored on "Sheet1" (change to meet your requirements) of the workbook you are copying from, you can filter column 12 and copy all of the data in a more simple command like this:

    Sub Test()
    
            'Declare source and destination variables
            Dim sourceWB As Workbook, destWB As Workbook
    
            Set sourceWB = ThisWorkbook
    
            'Open the workbook to copy the data TO
            Workbooks.Open Filename:="C:\users\andrew.godish\Desktop\Practice Files\masterPracticeExtractDataWBtoWB.xlsx"
            Set destWB = ActiveWorkbook
    
            sourceWB.Sheets("Sheet1").Range("A1:P1").AutoFilter Field:=12, Criteria1:="Airfare"
    
            'The first offset on the copy is to avoid copying the headers each time, the second offset is to find the last row in the
            'list then offset to the next row. Copies data to new workbook
            sourceWB.Sheets("Sheet1").AutoFilter.Range.Offset(1).Copy Destination:=destWB.Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)
    
            destWB.Save
    
            'Clear the filter from the source worksheet
            If sourceWB.Sheets("Sheet1").AutoFilterMode Then sourceWB.Sheets("Sheet1").ShowAllData
    
    End Sub
    

    I know this doesn't directly answer your question, but I think this may be an easier, less error-prone method.

    So this method follows these steps:

    • Open the destination workbook
    • Filter Sheet1 on column 12 for "Airfare" (be sure to change Sheet1 if necessary)
    • Copy and paste the filtered range to the destination worksheet and workbook
    • Remove the filter applied to column 12 in the source worksheet

    The confusing part may be the use of Offset(1). I use that on the copy to avoid copying the column headers (it offsets the copy area by one row down). I use it on the destination to avoid overwriting the last row (we must find the last used row, then increment down one row).

    0 讨论(0)
提交回复
热议问题