我有一个用VBA编写的excel宏,可将数据从工作表复制到另一个工作表。现在,不再需要介于72和77之间的行(有一张表始终位于需要移动的行之间),因此我想通过从最终工作表中删除它们来停止对其进行迭代。我怎样才能做到这一点?这是我的子程序的代码:
Windows(report).Activate
Sheets("bond forward").Select
k = 1000
For conta = 16 To 500
If Cells(conta, 14) = "BDCHFT_MM" Then
Rows(conta).Select
Selection.Copy
Rows(k).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
k = k + 1
End If
Next conta
k = 2000
For conta2 = 16 To 500
If Cells(conta2, 14) = "BAT_TIGO" Then
Rows(conta2).Select
Selection.Copy
Rows(k).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
k = k + 1
End If
Next conta2
答案 0 :(得分:1)
即使您是说您的代码是从一张纸复制到另一张纸,我也找不到另一张纸,您是从同一张纸复制下面的几行。
无论如何,我已经修改了您的代码,因此不会使用.Select
或.Activate
,您应该避免使用它们。还添加了对工作表的引用,因此您始终可以像示例一样在代码中对其进行引用。
有些重要的事情,请使用Option Explicit
强制声明所有变量,否则您将遇到许多错误:
Option Explicit
Sub Test()
Dim ws As Worksheet, k As Long, l As Long, conta As Long
'I believe the workbook with the bond forward sheet is not called report, so change the name and include it's extension
Set ws = Workbooks("Report.xlsx").Sheets("bond forward")
k = 1000
l = 2000
With ws
For conta = 16 To 500
If conta > 71 And conta < 78 Then GoTo NextRow 'this will skip the rows 72-77
If .Cells(conta, 14) = "BDCHFT_MM" Then
.Rows(conta).Copy 'you can copy in one step without selecting
.Rows(k).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'same for paste
k = k + 1
ElseIf .Cells(conta, 14) = "BAT_TIGO" Then 'also you don't need another loop to do this, just another variable for the paste row
.Rows(conta).Copy
.Rows(l).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
l = l + 1
End If
NextRow:
Next conta
End With
End Sub
答案 1 :(得分:1)
跳过循环的最简单方法是使用GoTo
语句编写适当的标志:
Dim firstRowToSkip As Long, lastRowToSkip As Long
firstRowToSkip = 72
lastRowToSkip = 77
For conta = 16 To 500
' skip loop
If conta >= firstRowToSkip And conta <= lastRowToSkip Then GoTo NextIteration
'rest of loop
NextIteration:
Next
答案 2 :(得分:0)
另一种可能的解决方案:
Option Explicit
Sub test()
Dim k1 As Long, k2 As Long, conta As Long
k1 = 1000
k2 = 2000
With ThisWorkbook.Worksheets("bond forward")
For conta = 16 To 500
If conta > 72 And conta < 77 Then
If .Cells(conta, 14) = "BDCHFT_MM" Then
.Rows(conta).Copy
.Rows(k1).PasteSpecial Paste:=xlPasteValues
k1 = k1 + 1
ElseIf Cells(conta, 14) = "BAT_TIGO" Then
.Rows(conta).Copy
.Rows(k2).PasteSpecial Paste:=xlPasteValues
k2 = k2 + 1
End If
End If
Next conta
End With
End Sub