循环遍历所有活动的工作表
我在VBA方面的工作经验非常薄弱,但现在却面临着一个真正需要的问题。
我需要将单元格的值从多个工作表(除了“摘要”)复制到一个工作表,但面临一个问题。 运行一个macros时,我得到了30行左右的值,但是所有的30个值都属于同一个工作表。 似乎循环只运行在大约1个工作表上。 你能帮我find代码中的错误吗?
Sub CopyTotalSalesPrice() For Each Worksheet In ActiveWorkbook.Worksheets If Worksheet.Name <> "Summary" Then Worksheet.Cells(Rows.Count, 7).End(xlUp).Select End If If Selection.Value > "0" Then Selection.Copy Worksheets("Summary").Cells(Rows.Count, 6).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues) Range("D4").Select Selection.Copy Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues) End If Next Worksheet Worksheets("Summary").Select End Sub
当使用Cells(Rows.Count,7).End(xlUp).Select和其他所有内容时,它们引用当前表单。 所以你要么放在他们的前面Worksheet.Cells(Rows.Count,7).End(xlUp)。select或者你先激活工作表Worksheet.Activate
或者你可以做如下:
Sub CopyTotalSalesPrice() For Each Worksheet In ActiveWorkbook.Worksheets With Worksheet If .Name <> "Summary" Then .Cells(Rows.Count, 7).End(xlUp).Copy Destination:=Worksheets("Summary").Cells(Rows.Count, 6).End(xlUp).Offset(2, 0) .Range("D4").Copy Destination:=Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).Offset(2, 0) End If End With Next Worksheet Worksheets("Summary").Select End Sub
尝试这个:
Sub CopyTotalSalesPrice() For Each Worksheet In ActiveWorkbook.Worksheets If Worksheet.Name <> "Summary" Then Worksheet.Select Worksheet.Cells(Worksheet.Rows.Count, 7).End(xlUp).Select End If If Selection.Value > "0" Then Selection.Copy Worksheets("Summary").Cells(Worksheet.Rows.Count, 6).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues) Range("D4").Select Selection.Copy Worksheets("Summary").Cells(Worksheet.Rows.Count, 4).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues) End If Next Worksheet Worksheets("Summary").Select End Sub
我replace了这个Cells(Rows.Count, 7).End(xlUp).Select
。selectWorksheet.Cells(Worksheet.Rows.Count, 7).End(xlUp).Select