VBA For Each工作表仅适用于第一张工作表

时间:2016-01-11 22:49:51

标签: excel vba excel-vba

我正在创建一个包含17张的工作簿,每个工作簿都有一个每月更改的产品列表。如果产品有错误,它会在值中显示为CMB,但产品仍然存在。我是要删除产品行。这段代码基于逐页工作,但是一旦我尝试循环它,它就不起作用了。

Sub wsLoop()
Dim ws as Worksheet
For Each ws In Worksheets
'Seeing if there are new products added to list
countcells = Range(Range("F8").End(xlDown).Offset(, -4), Range("A8").End(xlDown)).Cells.SpecialCells(xlCellTypeConstants).Count
'if no products added, then see if there in CMB in any row and delete that row
If countcells = 1 Then
If Not Range("E:E").Find("CMB") Is Nothing Then

Range(Range("E:E").Find("CMB"), Range("E8").End(xlDown)).Rows.EntireRow.Delete

End If
End If
Next ws
End Sub

1 个答案:

答案 0 :(得分:2)

您必须实际获取当前工作表的范围。例如,

IfWinActive WinTitle

否则,您将始终只是从当前选定的工作表中获取范围(通常是第一个工作表)。

请注意,您需要对countcells = ws.Range(ws.Range("F8").End(xlDown).Offset(, -4), ws.Range("A8").End(xlDown)).Cells.SpecialCells(xlCellTypeConstants).Count 的所有实例重复此操作。

顺便说一句,你可以做的一件事就是使用Range

With

With ws countcells = .Range(.Range("F8").End(xlDown).Offset(, -4), .Range("A8").End(xlDown)).Cells.SpecialCells(xlCellTypeConstants).Count 'repeat for all lines End With 无需反复重复对象的名称。您只需输入With,它就会自动知道您的意思是.property