1

我正在尝试根据某些特定条件删除 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
4

1 回答 1

4

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

如果结果不是数字,则该Int()函数将抛出您所看到的类型不匹配错误。

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

于 2012-12-07T14:31:54.810 回答