Excel VBA For-Next Loop将数据从一个WB提取到另一个WB

我正在做一个for循环,根据第12列中的string提取整行数据,等于“机票”。

这个想法是复制第12列(EXPENSE_TYPE)为Airfare的数据行并将其粘贴到第二个工作簿中。

我的代码如下所示,不能正确循环所有120行数据。 当我运行我的macros,它只提取符合我的标准的第一行数据。 让我知道如果你能find我的问题。 谢谢!

Sub exportDataToOtherWorkbook() Dim lastRow As Long Dim i As Long Dim p As Integer Dim q As Integer Dim erow As Long lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row For i = 2 To lastRow If Cells(i, 12) = "Airfare" Then Range(Cells(i, 1), Cells(i, 16)).Select Selection.Copy Workbooks.Open Filename:="C:\users\andrew.godish\Desktop\Practice Files\masterPracticeExtractDataWBtoWB.xlsx" p = Worksheets.Count For q = 1 To p If ActiveWorkbook.Worksheets(q).Name = "Sheet2" Then Worksheets("Sheet2").Select End If Next q erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row ActiveSheet.Cells(erow, 1).Select ActiveSheet.Paste ActiveWorkbook.Save Application.CutCopyMode = False End If Next i End Sub 

我会build议一个替代循环通过每一行。 循环是非常低效的,应尽可能避免。

假设您的数据存储在要复制的工作簿的“Sheet1”(更改为符合您的要求)中,则可以过滤第12列,并使用更简单的命令复制所有数据,如下所示:

 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 

我知道这并不直接回答你的问题,但我认为这可能是一个更容易,更不容易出错的方法。

所以这个方法遵循这些步骤:

  • 打开目标工作簿
  • 在“机票”栏第12列上过滤Sheet1 (如有必要,请务必更改Sheet1
  • 将过滤的范围复制并粘贴到目标工作表和工作簿
  • 删除应用于源工作表中第12列的筛选器

令人困惑的部分可能是Offset(1) 。 我在副本上使用它来避免复制列标题(它将复制区域向下偏移一行)。 我在目的地上使用它,以避免覆盖最后一行(我们必须find最后使用的行,然后递增一行)。