如何让我的循环搜索值而不是字符串?

时间:2019-05-06 16:34:07

标签: excel vba

我有一些在单元格中同时包含单词和值的数据,我正试图删除单元格中没有值的行。如果所有数字均为负数,则我的代码现在可以工作,但是如果有正数,则我的代码将无法工作。我该如何解决?

Sub tval 
    Dim s As Long
    Dim LastRow As Long

    S=2
    LastRow= cells.find(“*”,[A1],,, xlByRows,xlPreviousRow).row
    Do until s>LastRow
    DoEvents
    If InStr(1,Cells(s,4), “-“) > 0 Then
        S=s+1
    Else
        Cells(s,4).EntireRow.Delete
        LastRow=LastRow -1
    End if 
Loop
End sub

4 个答案:

答案 0 :(得分:1)

删除行时,应始终从末尾开始。

Sub tval 
    Dim s As Long
    Dim LastRow As Long

    LastRow= Cells(Rows.Count, 1).End(xlUp).Row
    For s= LastRow to 2 Step -1
          If Not IsNumeric(Cells(s,4)) then
                Cells(s,4).EntireRow.Delete
          End if 
    Next s
End sub

答案 1 :(得分:1)

这应该对您有用:

Sub tgr()

    Dim ws As Worksheet
    Dim rTextConstants As Range
    Dim rTextFormulas As Range
    Dim rCombined As Range

    Set ws = ActiveWorkbook.ActiveSheet

    'Exclude row 1 so that only text values found in rows 2+ are found
    With ws.Range("A2", ws.Cells(ws.Rows.Count, ws.Columns.Count))
        On Error Resume Next    'prevent error if no cells found
        Set rTextConstants = .SpecialCells(xlCellTypeConstants, xlTextValues)
        Set rTextFormulas = .SpecialCells(xlCellTypeFormulas, xlTextValues)
        On Error GoTo 0         'remove on error resume next condition
    End With

    If Not rTextConstants Is Nothing Then Set rCombined = rTextConstants
    If Not rTextFormulas Is Nothing Then
        If rCombined Is Nothing Then Set rCombined = rTextFormulas Else Set rCombined = Union(rCombined, rTextFormulas)
    End If

    If Not rCombined Is Nothing Then
        rCombined.EntireRow.Delete
    Else
        MsgBox "No cells containing text found in sheet '" & ws.Name & "'", , "Error"
    End If

End Sub

答案 2 :(得分:1)

我可以建议一些不同的方法吗?

之前:

enter image description here

代码:

Dim RNG1 As Range, RNG2 As Range

Option Explicit

Sub TestCase()

With ActiveWorkbook.Sheets(1)
    Set RNG1 = .Range("A1:A" & .Cells(Rows.Count, 1).End(xlUp).Row)
    If RNG1.SpecialCells(xlCellTypeConstants, 1).Count <> RNG1.Cells.Count Then
        Set RNG2 = Application.Intersect(RNG1, RNG1.SpecialCells(xlCellTypeConstants, 2))
        RNG2.EntireRow.Delete
    End If
End With

End Sub

之后:

enter image description here

您需要将其更改为明显适合您的范围。尽管如此,这应该是一个很好的起点。

答案 3 :(得分:1)

您还可以使用AutoFilter过滤数字,并删除可见的单元格以完成此任务。该代码占标题行。

With ThisWorkbook.Sheets("Sheet1")
    With .Range("A1").CurrentRegion
        .AutoFilter
        .AutoFilter Field:=4, Criteria1:="<>*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        .AutoFilter
    End With
End With