VBA对于每个工作表仅在第一张工作表上工作
我正在创build一个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
你必须得到当前工作表的范围。 例如,
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
消除了重复对象的名称一遍又一遍的需要。 你只要键入.property
,它会自动知道你的意思是ws.property
。