VBA - 循环浏览所有表格并排除一个表格

时间:2018-04-25 12:42:50

标签: excel vba excel-vba

我需要在工作簿中的所有工作表上执行完全相同的任务,除了一个,我有以下代码,但是我收到以下错误:

  

结束如果没有阻止如果

    Sub Servers3_DeleteIrrelevantColumns()

    'Initialize variables
    Dim currentColumn As Integer
    Dim columnHeading As String
    Dim wrkSht As Worksheet

    'Rename headers on all sheets if matched

        If wrkSht.Name <> "New Servers" Then
    For Each wrkSht In ActiveWorkbook.Worksheets

            wrkSht.Cells(1, 1).EntireRow.Replace What:="*ServerName*", Replacement:="Server Name", Lookat:=xlWhole

            For currentColumn = wrkSht.UsedRange.Columns.Count To 1 Step -1

                columnHeading = wrkSht.UsedRange.Cells(1, currentColumn).Value

                'Check whether to keep column
                Select Case columnHeading

                    Case "Server Name"

                    'Do nothing

                    Case Else

                    wrkSht.Columns(currentColumn).Delete

                End Select

            Next

        End If

End Sub

1 个答案:

答案 0 :(得分:4)

以下是我的问题的有效解决方案:

Sub Servers3_DeleteIrrelevantColumns()

    'Initialize variables
    Dim currentColumn As Integer
    Dim columnHeading As String
    Dim wrkSht As Worksheet

    'Rename headers on all sheets if matched

    For Each wrkSht In ActiveWorkbook.Worksheets

        If wrkSht.Name <> "New Servers" Then

            wrkSht.Cells(1, 1).EntireRow.Replace What:="*ServerName*", Replacement:="Server Name", Lookat:=xlWhole

            For currentColumn = wrkSht.UsedRange.Columns.Count To 1 Step -1

                columnHeading = wrkSht.UsedRange.Cells(1, currentColumn).Value

                'Check whether to keep column
                Select Case columnHeading

                    Case "Server Name"

                    'Do nothing

                    Case Else

                    wrkSht.Columns(currentColumn).Delete

                End Select

            Next

        End If

    Next wrkSht

End Sub