如何删除不包含特定值的所有单元格(在VBA / Excel中)

时间:2013-12-18 21:39:16

标签: excel excel-vba vba

我完全不明白如何在vba deleting rows that do not contain set values defined in range中遵循答案(我需要使用VBA)。从我收集的内容来看,我需要指定一个数组,然后使用一些if if then。

在我的情况下,我想创建一些只搜索指定列并删除所有不包含特定字母/数字的值的东西。 1,2,3,4,5,s,f,p,a,b,c,o是我想保留的数字/字母。不包含这些值的单元格(甚至应该删除11或1),我只想删除单元格(不是整行)并将单元格下方的单元格移位(我相信你可以使用默认的.delete命令执行此操作) )。

例如,我的列看起来像这样:


一个
1
2
5
小号
˚F
小号
8

31
4
f

我想屏蔽我的数据,以便自动删除所有空白单元格和所有不包含上述数字或字母的单元格(例如本例中为31和8)。

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

Sub Tester()

Dim sKeep As String, x As Long
Dim rngSearch As Range, c As Range

    'C1:C5 has values to keep
    sKeep = Chr(0) & Join(Application.Transpose(Range("C1:C5").Value), _
                                Chr(0)) & Chr(0)

    Set rngSearch = Range("A1:A100")

    For x = rngSearch.Cells.Count To 1 Step -1
        Set c = rngSearch.Cells(x)
        If InStr(sKeep, Chr(0) & c.Value & Chr(0)) = 0 Then
            c.Delete shift:=xlShiftUp
        End If
    Next x

End Sub

答案 1 :(得分:2)

这样做

Sub Main()

Dim dontDelete
dontDelete = Array("1", "2", "3", "4", "5", "s", "f", "p", "a", "b", "c", "o")

Dim i As Long, j As Long

Dim isThere As Boolean

For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    For j = LBound(dontDelete) To UBound(dontDelete)
        If StrComp(Range("A" & i), dontDelete(j), vbTextCompare) = 0 Then
            isThere = True
        End If
    Next j
    If Not isThere Then
        Range("A" & i).Delete shift:=xlUp
    End If
    isThere = False
Next i

End Sub

答案 2 :(得分:1)

Sub DeleteValues()
Dim x As Integer
Dim i As Integer
Dim Arr(1 To 3) As String

Arr(1) = "1"
Arr(2) = "2"
Arr(3) = "3"

Range("A1").Select

For x = 1 To 10
    For i = 1 To 3
        If ActiveCell.Value = Arr(i) Then
            ActiveCell.Delete
        End If
    Next i
    ActiveCell.Offset(1, 0).Select
Next x

End Sub

这将遍历范围(“a1:a10”)并删除值=任何数组值的任何单元格(1,2,3)

您应该希望能够使用此代码并满足您的需求吗?

答案 3 :(得分:1)

另一种方式:)它不会删除循环中的单元格。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim rngDEL As Range
    Dim strDel As String
    Dim arrDel
    Dim i As Long

    strDel = "1,11,Blah" '<~~ etc... You can pick this from a range as well
    arrDel = Split(strDel, ",")

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws.Columns(1) '<~~ Change this to the relevant column
        For i = LBound(arrDel) To UBound(arrDel)
            .Replace What:=arrDel(i), Replacement:="", LookAt:=xlWhole, SearchOrder:= _
            xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        Next i

        On Error Resume Next
        Set rngDEL = .Cells.SpecialCells(xlCellTypeBlanks)
        On Error GoTo 0

        If Not rngDEL Is Nothing Then rngDEL.Delete Shift:=xlShiftUp
    End With
End Sub