我写了以下子词:
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
当我按照以下程序打电话时:
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
我收到此错误:使用指定的范围无法完成命令。选择范围内的单个单元格并再次尝试该命令。但是,如果我在一张纸上使用Public Sub作为没有For循环的过程而不是调用它,它就可以正常工作。
答案 0 :(得分:1)
从循环或任何其他部分调用此函数的事实对其性能没有任何影响。循环中发生的是输入条件发生变化并触发错误,因为被引用的部分无法处理任何情况。
最有可能引发错误,因为“字段1”(即范围SearchRange & lngLr
的第二行)为空。因此,对错误进行更正(请记住,Rows
从1开始,Field
从0开始):
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