VBA代码仅适用于第一张表

时间:2018-05-18 11:01:03

标签: excel vba excel-vba

我正在尝试编辑一个包含17张的工作簿,每个工作簿都包含A列中的城市列表,我想删除它们在我在下面的代码中创建的数组中的值相等的行。这段代码基于逐页工作,但是一旦我尝试循环它,它就不起作用了。

expand.grid

3 个答案:

答案 0 :(得分:4)

您必须在循环浏览每个工作表时引用它们。

Sub myDeleteRows()

    Dim MyCol As String
    Dim lRow As Long
    Dim iCntr As Long
    Dim i As Integer
    Dim core_cities As Variant
    Dim sh As Worksheet

    core_cities = Array("Bristol", "Birmingham", "Cardiff", "Leeds", "Liverpool", "Manchester", "Newcastle-upon-Tyne", "Nottingham", "Sheffield")

    lRow = 140

    For Each sh In ActiveWorkbook.Sheets

        with sh
            For i = lRow To 4 Step -1

                If IsError(Application.Match(.Range("A" & i).Value, core_cities, False)) Then
                    .Rows(i).Delete
                End If

            Next i
        end with

    Next sh

    MsgBox ("complete")

End Sub

注意.Range和.Rows在With ... End With内部而不仅仅是Range或Rows。前缀句点(例如.)提供与sh。

相关联的父工作表引用

答案 1 :(得分:4)

这是一个简单的修复。您的循环未引用sh,这意味着只更改了活动工作表。下面的唯一更改(除了缩进)是两个sh的添加。

为了提高您的代码效率,您可以改变lRow,以便它只选取包含条目的行(除非您的所有工作表只有140个条目)。

Sub myDeleteRows()

Dim MyCol As String
Dim lRow As Long
Dim iCntr As Long
Dim i As Long
Dim core_cities As Variant
Dim sh As Worksheet

core_cities = Array("Bristol", "Birmingham", "Cardiff", "Leeds", "Liverpool", "Manchester", "Newcastle-upon-Tyne", "Nottingham", "Sheffield")

lRow = 140

For Each sh In ActiveWorkbook.Sheets
    For i = lRow To 4 Step -1
        If IsError(Application.Match(sh.Range("A" & i).Value, core_cities, False)) Then
            sh.Rows(i).Delete
        End If
    Next i
Next sh

MsgBox ("complete")

End Sub

答案 2 :(得分:4)

您需要使用Sheet参考限定范围,否则代码中使用的范围将始终仅指活动工作表。

For Each sh In ActiveWorkbook.Sheets
    For i = lRow To 4 Step -1
        If IsError(Application.Match(sh.Range("A" & i).Value, core_cities, False)) Then
            sh.Rows(i).Delete
        End If
    Next i
Next sh