0

I wrote the following sub:

    Public Sub filterEmployeeSheets(Sheets As Excel.Worksheet, SearchRange As String, Indicator As String, FilterString As String)

    'This Sub is used to filter sheets by deleting any rows
    'that do not contain the value stated in variable filterString

    '@Parameter Sheets to declare sheet(s) name
    '@Parameter SearchRange to set the column to filter
    '@Parameter Indicator determines the =, <> setting
    '@Parameter FilterString to set the string to keep

    Dim lngLr As Long

    With Sheets

        lngLr = .Cells.Find(What:="*", SearchDirection:=Excel.XlSearchDirection.xlPrevious, SearchOrder:=Excel.XlSearchOrder.xlByRows).Row

        If lngLr > 1 Then
            With .Range(SearchRange & lngLr)
                **.AutoFilter(Field:=1, Criteria1:=Indicator & FilterString)** 'Error is here
                .EntireRow.Delete()
            End With
        End If
    End With
End Sub

Public Function ClientSheets(Index As Long) As Excel.Worksheet

    'This function indexes all of the Employee sheets
    'to use in various loops during he instal process
    '@param EmployeeSheets, are the sheets to index

    Select Case Index

        Case 1 : Return xlWSAllEEAnnul
        Case 2 : Return xlWSAllEEHourly
    End Select

    Throw New ArgumentOutOfRangeException("Index")

End Function

When I call it on the procedure below:

        Dim xlRefSheets As Excel.Worksheet

        For i As Long = 1 To 2 Step 1

            Dim strOperatorSymbol As String = "<>"

            xlRefSheets = ClientSheets(i)

            filterEmployeeSheets(xlRefSheets, "K5:K", "<>", "Y")

        Next

End Sub

I get this error: The command could not be completed by using the range specified. Select a single cell within the range and try the command again. However, If I use the Public Sub as a procedure without the For Loop on a single sheet instead of calling it, it works just fine.

4

1 回答 1

1

从循环或任何其他部分调用此函数的事实对其性能没有任何影响。循环中发生的是输入条件发生变化并触发错误,因为引用的部分无法处理任何情况。

很可能会引发错误,因为“字段 1”(即范围的第二行SearchRange & lngLr)为空。因此更正您的错误(请记住Rows从 1 和Field0 开始):

If (.Rows.Count > 1 AndAlso .Rows(2).Value IsNot Nothing AndAlso .Rows(2).Value.ToString().Trim().Length > 0) Then
    .AutoFilter(Field:=1, Criteria1:=Indicator & FilterString)
End If

还有一部分:

 lngLr = .Cells.Find(What:="*", SearchDirection:=Excel.XlSearchDirection.xlPrevious, SearchOrder:=Excel.XlSearchOrder.xlByRows).Row

容易触发错误。如果未找到匹配项,则范围将为Nothing,因此.Row将触发错误。执行以下操作总是更安全:

Dim lngLr As Long = 0
Dim findRange As Excel.Range = .Cells.Find(What:="*", SearchDirection:=Excel.XlSearchDirection.xlPrevious, SearchOrder:=Excel.XlSearchOrder.xlByRows)
If (findRange IsNot Nothing) Then
    lngLr = findRange.Row
End If
于 2013-09-25T16:26:11.890 回答