【发布时间】:2016-01-07 19:34:21
【问题描述】:
我已经阅读了有关 VBA 中错误处理的多个问答,但由于某种原因,我的代码无法正常工作。我正在尝试过滤特定的单词(变量名“item”),如果过滤的范围没有单词,它必须跳过代码并跳转到错误处理程序(并转到下一个单词)。这必须持续到 for 完成。我的代码如下:
Sub Group_Button1_Click()
Worksheets("Grouping_Name").Select
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
lastrow_grouping = Selection.Count + 1
Dim filterRange As Range
Dim copyRange As Range
Dim lastrow_To_be_grouped As Long
For grouping_counter = 2 To lastrow_grouping
' on to_be_grouped sheet turn off any autofilters that are already set Sheets("To_be_grouped").AutoFilterMode = False
' find the last row with data in column A of To_be_grouped sheet
lastrow_To_be_grouped = Sheets("To_be_grouped").Range("A" & Sheets("To_be_grouped").Rows.Count).End(xlUp).Row
' the range that we are auto-filtering (all columns)
Set filterRange = Sheets("To_be_grouped").Range("A1:B" & lastrow_To_be_grouped)
' Copy filtered data (exclude header) in To_be_grouped sheet
Set copyRange = Sheets("To_be_grouped").Range("A2:B" & lastrow_To_be_grouped)
' Assign variable "item" which is the word to filter
Item = Sheets("Grouping_Name").Range("A" & grouping_counter).Value
' Filter column with variable item
filterRange.AutoFilter field:=2, Criteria1:="=*" & Item & "*", Operator:=xlAnd
' copy the visible cells to Final_Grouping sheet
' determine first row with no data in Final Grouping sheet and copy to sheet
On Error GoTo errorhandler
' This is where I need help, if there is no line with the filtered word the code must jump to errorhandler
If IsNumeric(copyRange.SpecialCells(xlCellTypeVisible).Count) = True Then
copyRange.SpecialCells(xlCellTypeVisible).Copy Sheets("Final_Grouping").Range("A" & item_counter_total)
' delete the tables
Sheets("To_be_grouped").Range("$A$1:$B$" & lastrow_To_be_grouped).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
' Count the number of rows added
item_counter = copyRange.SpecialCells(xlCellTypeVisible).Count / 2
' ------------------------------------------
For group_table_counter = item_counter_total To item_counter_total + item_counter - 1 Step 1
Sheets("Final_Grouping").Range("C" & group_table_counter).Value = Item
Next group_table_counter
' ------------------------------------------
item_counter_total = item_counter_total + item_counter
End If
errorhandler:
Next grouping_counter
End Sub
任何帮助将不胜感激。谢谢
【问题讨论】:
-
为什么需要错误处理程序?您不能将 IF 逻辑更改为 If copyRange.SpecialCells(xlCellTypeVisible).Count > 0 then ...Granted,这还没有经过测试,但应该做同样的事情,对吧?
-
另外,澄清一下: IsNumeric(copyRange.SpecialCells(xlCellTypeVisible).Count) = True 将始终为 TRUE,因为您返回的计数为 0,恰好是一个数字...
标签: excel vba error-handling