Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim wks As Worksheet
On Error GoTo Err_Execute
For Each wks In Worksheets
ThisWorkbook.Worksheets.Add After:=Worksheets(Worksheets.Count)
Set wksCopyTo = ActiveSheet
wks.Rows(3).EntireRow.Copy wksCopyTo.Rows(3)
'Start search in row 4
LSearchRow = 4
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 4
While Len(wks.Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column E = "Mail Box", copy entire row to Sheet2
If wks.Range("AB" & CStr(LSearchRow)).Value = "Yes" And wks.Range("AK" & CStr(LSearchRow)).Value = "Yes" And wks.Range("BB" & CStr(LSearchRow)).Value = "Y" Then
'Select row in Sheet1 to copy
wks.Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
MsgBox "Copying Row"
'Paste row into Sheet2 in next row
wksCopyTo.Select
wksCopyTo.Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
wksCopyTo.Paste
MsgBox "Pasting Row"
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
wks.Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Next wks
Exit Sub
Err_Execute:
MsgBox "An error occurred."
你好
我有上面的代码,它基于其他地方给出的代码。在复制那些符合if语句中给出的条件的行时,代码已经过调整,我需要它来为每个现有工作表创建一个新的工作表。我遇到的问题是:
有人可以帮忙吗?
答案 0 :(得分:0)
我会逐一回答你的问题:
是。您可以使用ThisWorkbook.Worksheets.Count
之类的内容来返回当前工作簿所具有的工作表数。然而,遍历工作表的最佳方法是通过Worksheets
Collection:
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
'Do something
'...
Next wks
Set wks = Nothing
您永远不会退出循环(如果您在A列中有> 32,000行数据),直到您遇到溢出错误(整数只能达到32,767 +/-)。
参见第2点。您正在循环超出整数的限制。将数据类型更改为Long和/或如第2点所述,在某个时刻退出循环。