VBA宏不会遍历工作簿中的工作表

时间:2018-08-17 15:15:31

标签: excel vba excel-vba

Sub CullData():

Dim ws As Worksheet
Dim Counter As Integer
Dim obsoleterows As Range

For Each ws In ThisWorkbook.Worksheets

For Counter = 1 To 40 Step 2
    ws.Range("P2").Offset(Counter - 1, 0) = ws.Range("I1").Offset(Counter - 1, 0)
    ws.Range("Q2").Offset(Counter - 1, 0) = ws.Range("K1").Offset(Counter - 1, 0)

    If obsoleterows Is Nothing Then
        Set obsoleterows = Rows(Counter)
    Else
        Set obsoleterows = Union(obsoleterows, Rows(Counter))
    End If

Next Counter
obsoleterows.Delete
Set obsoleterows = Nothing

Next ws

End Sub

由于某种原因,循环会运行,但不会从一张纸移到下一张纸-我认为它只会在工作簿的第一张纸上运行相同的代码大约十次(因为我有10张纸)。如果我删除该循环,则该循环将运行一次并关闭,以便代码识别出该循环,而不会遵循该循环。我已经尝试了上述方法的变体,但每次都会遇到相同的问题。

1 个答案:

答案 0 :(得分:1)

并非循环中的所有范围引用都限于ws

If obsoleterows Is Nothing Then
    Set obsoleterows = Rows(Counter)
Else
    Set obsoleterows = Union(obsoleterows, Rows(Counter))
End If

应为:

If obsoleterows Is Nothing Then
    Set obsoleterows = ws.Rows(Counter)
Else
    Set obsoleterows = Union(obsoleterows, ws.Rows(Counter))
End If

....否则,它只是默认为ActiveSheet。

obsoleterows.Delete 

会更安全

If Not obsoleterows Is Nothing Then obsoleterows.Delete