VBA类型运行时13错误

时间:2017-07-28 19:23:50

标签: vba excel-vba excel

我想知道是否有人可以帮我解决这个问题。我编写了一个宏,其目的是根据一行中的所有单元格是否包含值" < 0.01 "来删除所选行。问题是当程序试图处理错误输出的if语句时。

任何帮助都将不胜感激。

 Sub deleteRows()
    Dim rng As Long
    Dim FirstCol, LastCol As Long
    Set UsedRng = ActiveSheet.UsedRange
    FirstCol = UsedRng(1).Column
    LastCol = UsedRng(UsedRng.Cells.Count).Column

    rng = Application.Selection.Rows.Count

    For i = rng To 1 Step -1
    if Range(Cells(i, FirstCol), Cells(i, LastCol)) = "<0.01" Then
    Rows(i).EntireRow.Delete
    End If

    Next i
    End Sub


New code that i wrote

`Sub for3()
Dim ma, r, c As Range
Dim counter As Long
Dim deletenum As Long
Dim firstcol As Variant
Set ma = Application.Selection
Set r = ma.Rows
Set c = ma.Columns
counter = 0
deletenum = c.Count
firstcol = ma(1).Column

For Each r In ma


    For Each c In r

        If c.Column = firstcol Then
        counter = 0


        End If

        If c.Text = "<0.01" Then

        counter = counter + 1

        End If

        If counter = deletenum Then
        r.EntireRow.Delete
     ma.Offset(1, 0).Activate

        End If
     Next c
Next r

End Sub

`

2 个答案:

答案 0 :(得分:1)

您可以改为每行使用Find功能:

Dim FndRng  As Range

For i = rng To 1 Step -1
    Set FndRng = Range(Cells(i, FirstCol), Cells(i, LastCol)).Find(What:="<0.01", LookIn:=xlValues, LookAt:=xlWhole)
    If Not FndRng Is Nothing Then ' find was successful
        Rows(i).Delete
    End If
Next 

修改1 :检查行中的所有单元格是否等于"<0.01"

For i = rng To 1 Step -1
    If WorksheetFunction.CountIf(Range(Cells(i, FirstCol), Cells(i, LastCol)), "<0.01") = Range(Cells(i, FirstCol), Cells(i, LastCol)).Cells.Count Then
        Rows(i).Delete
    End If
Next I

编辑2

Option Explicit

Sub t()

Dim Rng As Range
Dim firstCol As Long, LastCol As Long
Dim firstRow As Long, LastRow As Long
Dim i As Long
Dim C As Range

Set Rng = Selection ' only if you realy need to

' calculate the first and last column of the Selection
firstCol = Rng(1).Column
LastCol = Rng.Columns.Count + firstCol - 1

' calculate the first and last Row of the Selection
firstRow = Rng(1).Row
LastRow = Rng.Rows.Count + firstRow - 1

' loop backwards, for the Selection last row, until the first row of the selection
For i = LastRow To firstRow Step -1
    ' loop through current's row cells
    For Each C In Range(Cells(i, firstCol), Cells(i, LastCol))
        If C.Value2 <> "<0.01" Then
            GoTo ExitLoop
        End If
    Next C

    Rows(i).Delete

ExitLoop:
Next i

End Sub

答案 1 :(得分:0)

您的测试表达式可能如下所示:

Join(WorksheetFunction.Transpose(WorksheetFunction.Transpose(Range(Cells(i, FirstCol), Cells(i, LastCol)).Value)), " ") Like "*<0.01*"