我已經經歷了多個Q &作爲錯誤處理VBA閱讀,但由於某種原因,我的代碼不能正常工作。我試圖過濾一個特定的單詞(變量名稱「item」),如果過濾的範圍沒有該單詞,它必須跳過該代碼並跳轉到錯誤處理程序(並轉到下一個單詞)。這必須繼續,直到完成。我的代碼如下:錯誤處理程序在VBA 2016
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邏輯是如果像copyRange.SpecialCells(xlCellTypeVisible).Count> 0然後......當然,這還沒有經過測試,但應該做同樣的事情,對不對? – sous2817
也澄清了一點:IsNumeric(copyRange。SpecialCells(xlCellTypeVisible).Count)= True將始終爲TRUE,因爲您要返回的計數爲0,這恰好是一個數字... – sous2817