循环遍历行,根据条件复制一行

时间:2017-03-28 21:06:52

标签: excel vba excel-vba

我的代码将遍历我的工作表,但它会执行所有行的复制,而不仅仅是基于我的标准的行。我怎么才能把它复制到我想要的那一行?

Sub Major2_Paster()

Dim LastRow As Integer
Dim i As Integer
Dim erow As Integer

LastRow = Cells(Rows.count, 1).End(xlUp).Row

For i = 2 To LastRow
If Cells(i, 12) = “MLA” Then
range(Cells(i, 1), Cells(i, 21)).Select
Selection.Copy

Workbooks.Open Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx"
erow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row

ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False

End If

Next i
End Sub

1 个答案:

答案 0 :(得分:2)

有几件事:

  • 只打开工作簿一次,这将是最重要的性能提升
  • 创建对工作簿/工作表的引用,而不是使用ActiveWorkbook / Sub Major2_Paster() Dim LastRow As Integer, i As Integer, erow As Integer Dim destinationWorkbook As Workbook Dim sourceWorksheet As Worksheet, destinationWorksheet As Worksheet Set destinationWorkbook = Workbooks.Open(Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx") Set sourceWorksheet = ThisWorkbook.Worksheets("SheetName") Set destinationWorksheet = destinationWorkbook.Worksheets("SheetName") With sourceWorksheet LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row End With For i = 2 To LastRow If sourceWorksheet.Cells(i, 12).Value = “MLA” Then With destinationWorksheet erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row End With destinationWorksheet.Cells(erow, 1).Resize(1, 21).Value = sourceWorksheet.Range(sourceWorksheet.Cells(i, 1), sourceWorksheet.Cells(i, 21)).Value End If Next i destinationWorkbook.Close SaveChanges:=True Application.CutCopyMode = False End Sub
  • 缩进是所以很重要。它使代码更具可读性,并且是查找自己错误的第一步
map[string]int