运行VBA代码时,键入不匹配错误以根据特定条件删除行

时间:2012-12-07 14:26:03

标签: excel loops if-statement excel-vba type-mismatch vba

我正在尝试根据某些特定条件删除Excel工作表中的某些行。在某些时候,它会出现以下类型不匹配错误:

ss

据我所知,从部分创建的工作表中,错误发生在

的DO循环中
Or Len(Cells(r, 1)) = 5 _
Or Int(Right(Cells(r, 1), 4)) > 4000 _
Or Cells(r, 3) = 0

一部分。我该怎么做才能纠正错误?另外,如果你可以推荐我改进代码以加快运行速度,我真的很感激。完整代码如下:

Sub delrows()

Dim r, RowCount As Long
r = 2

ActiveSheet.Columns(1).Select
RowCount = UsedRange.Rows.Count
userresponse = MsgBox("You have " & RowCount & " rows", vbOKOnly, "Info")

Rows(RowCount).Delete Shift:=xlUp

' Trim spaces

Columns("A:A").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, searchFormat:=False, _
    ReplaceFormat:=False

' Delete surplus columns

Range("L:T,V:AA,AE:AG,AR:AR,AU:AU,AZ:AZ").Select
    Selection.Delete Shift:=xlToLeft

' Delete surplus rows

Do
    If Left(Cells(r, 1), 1) = "D" _
       Or Left(Cells(r, 1), 1) = "H" _
       Or Left(Cells(r, 1), 1) = "I" _
       Or Left(Cells(r, 1), 2) = "MD" _
       Or Left(Cells(r, 1), 2) = "ND" _
       Or Left(Cells(r, 1), 3) = "MSF" _
       Or Left(Cells(r, 1), 5) = "MSGZZ" _
       Or Len(Cells(r, 1)) = 5 _
       Or Int(Right(Cells(r, 1), 4)) > 4000 _
       Or Cells(r, 3) = 0 Then
     Rows(r).Delete Shift:=xlUp
    Else: r = r + 1
    End If
Loop Until (r = RowCount)

End Sub

1 个答案:

答案 0 :(得分:4)

条件Or Int(Right(Cells(r, 1), 4))是一个问题,因为它假定它正在评估的单元格内容部分是一个数字。

如果结果不是数字,那么Int()函数会抛出您所看到的那种类型不匹配错误。

如果在应用Int()函数之前测试它是否实际上是数字,那会更好。您可以使用IsNumeric()功能执行此操作。