我需要能够在工作簿的每个工作表中查看指定范围的单元格,如果它们符合条件,则将该行复制到摘要表。下面的代码大部分都适用,除了有一些实例,它复制不符合条件的行和一个跳过应该复制的行的实例。
有没有办法使用调试工具,以便在循环浏览代码时随时可以看到:什么是活动表?什么是活跃细胞?什么是活动行?等。
另外,我是否应该使用-For中的每个单元格而不是-Lhile Len-来遍历每张纸上的指定范围?
Sub LoopThroughSheets()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim ws As Worksheet
'Start copying data to row 2 in HH (row counter variable)
LCopyToRow = 2
For Each ws In ActiveWorkbook.Worksheets
'Start search in row 7
LSearchRow = 7
While Len(ws.Range("M" & CStr(LSearchRow)).Value) > 0
'If value in column M > 0.8, copy entire row to HH
If ws.Range("M" & CStr(LSearchRow)).Value > 0.8 Then
'Select row in active Sheet to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into HH in next row
Sheets("HH").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to active ws to continue searching
ws.Activate
End If
LSearchRow = LSearchRow + 1
Wend
Next ws
'Position on cell A1 in sheet HH
Sheets("HH").Select
Application.CutCopyMode = False
Range("A1").Select
MsgBox "All matching data has been copied."
End Sub
答案 0 :(得分:0)
关于调试的第一个问题,您可以使用:
Debug.Print "Worksheet: " & ActiveSheet.Name
在您的代码中的任何时间打印出您所在的表格"立即" Visual Basic编辑器中的窗口。这非常适合在所有情况下进行调试。
其次,For Each循环是循环通过任何东西的最快方法,但它有缺点。也就是说,如果您要删除/插入任何内容,它将返回有趣的结果(复制/粘贴将没问题)。如果您没有预先知道需要处理多少行,那么任何类型的While循环都可以使用。
就你的代码而言,我就是这样做的(你仍然需要在while循环的上方和下方包含你的代码):
Dim Items As Range
Dim Item As Range
'This will set the code to loop from M7 to the last row, if you
'didn't want to go to the end there is probably a better way to do it.
Set Items = ws.Range("M7:M26")
For Each Item In Items
'If value in column M > 0.8, copy entire row to HH
If Item.Value > 0.8 Then
'Select row in active Sheet to copy
Item.EntireRow.Copy
'Paste row into HH in next row
Sheets("HH").Rows(LCopyToRow & ":" & LCopyToRow).PasteSpecial
'Move counter to next row
LCopyToRow = LCopyToRow + 1
End If
Next Item
答案 1 :(得分:0)
非常类似于之前的答案,措辞不同。虽然结果不错。
Sub Button1_Click()
Dim Rws As Long, Rng As Range, ws As Worksheet, sh As Worksheet, c As Range, x As Integer
Set ws = Worksheets("HH")
x = 2
Application.ScreenUpdating = 0
For Each sh In Sheets
If sh.Name <> ws.Name Then
With sh
Rws = .Cells(Rows.Count, "M").End(xlUp).Row
Set Rng = .Range(.Cells(7, "M"), .Cells(Rws, "M"))
For Each c In Rng.Cells
If c.Value > 0.8 Then
c.EntireRow.Copy Destination:=ws.Cells(x, "A")
x = x + 1
End If
Next c
End With
End If
Next sh
End Sub