我正在开发一个 for 循环,该循环根据第 12 列中等于“Airfare”的字符串提取整行数据。
这个想法是复制第 12 列 (EXPENSE_TYPE) 是机票的数据行并将其粘贴到第二个工作簿中。
我的代码(如下)未正确循环所有 120 行数据。当我运行宏时,它仅提取满足我的条件的第一行数据。如果您能找到我的问题,请告诉我。谢谢!
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
我建议使用一种替代方法来循环遍历每一行。循环的效率非常低,如果可能的话应该避免。
假设您的数据存储在要从中复制的工作簿的“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
我知道这并不能直接回答你的问题,但我认为这可能是一种更简单、不易出错的方法。
所以该方法遵循以下步骤:
- 打开目标工作簿
- Filter
Sheet1
第 12 栏“机票”(请务必更改Sheet1
如果需要的话)
- 将筛选后的范围复制并粘贴到目标工作表和工作簿
- 删除应用于源工作表中第 12 列的筛选器
令人困惑的部分可能是使用Offset(1)
。我在副本上使用它来避免复制列标题(它将复制区域向下偏移一行)。我在目标上使用它以避免覆盖最后一行(我们必须找到最后使用的行,然后向下递增一行)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)