VBA Excel循环基于C列中的值删除范围

时间:2017-04-14 20:06:02

标签: vba excel-vba loops excel

我试图根据列是否删除特定范围" C"符合特定标准。

目前我有以下内容:

bmImage = result.copy(result.getConfig(), true);
listener.setBitmap(bmImage)
// Do stuff with the bitmap in setBitmap()

我想把它变成一个循环来搜索单元格" C1"通过" C100"对于单词"所有值为百万美元。"并删除相应的C至H范围。例如,如果它在" C15"中找到了值,它将删除范围(" C15:H15")。

不幸的是,我还在学习,我尝试的所有循环都会产生错误。

5 个答案:

答案 0 :(得分:3)

您可以使用Excel的过滤功能:

With Sheet1.Range("C1:H100")
    .AutoFilter 1, "All values USD Millions."
    .Offset(1).Delete
    .AutoFilter
End With

但是,如果你想做一个经典的"在迭代行时迭代和删除,请记住,在这些情况下,您应该迭代"向后"

Dim i as long
For i = Range("C999999").End(xlUp).Row to 1 Step -1
    If Cells(i, "C").Value2 = "All values USD Millions." Then Rows(i).Delete
Next

答案 1 :(得分:2)

另一种快速方法是在没有逐行循环的情况下使用Find函数:

Option Explicit

Sub UseFindFunc()

Dim FindRng         As Range
Dim Rng             As Range
Dim LastRow         As Long
Dim TexttoFind      As String

TexttoFind = "All values USD Millions." ' <-- try to use variable, easy to modify later

With Sheet1
    LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row '<-- get last row with data in Column C
    Set Rng = .Range("C1:H" & LastRow)

    Set FindRng = Rng.Find(What:=TexttoFind, LookIn:=xlValues, LookAt:=xlWhole)
    While Not FindRng Is Nothing '<-- find was successful
        FindRng.Resize(, 5).Delete xlShiftUp '<-- delete column "C:H" in found row
        Set FindRng = Rng.Find(What:=TexttoFind, LookIn:=xlValues, LookAt:=xlWhole)
    Wend
End With

End Sub

答案 2 :(得分:1)

尝试使用:

<body>
    <avatar-pic containerless></avatar-pic>
</body>

答案 3 :(得分:1)

如果您不想删除A列和B列中的单元格,这对我有用:

Sub test()
Dim i As Integer
For i = 1 To 100
    If Range("C" & i) = "All values USD Millions." Then
        Range("C" & i & ":H" & i).Delete
    Else
        Range("A3").Select
    End If
Next
End Sub

答案 4 :(得分:1)

如果您的数据不是静态的,您可以直到最后一行执行脚本或将i = 1设置为100以停在第100行

    Sub test()
    Dim lRow As Long

     lRow = WorksheetFunction.Max(Range("C65536").End(xlUp).Row, 
     Range("D65536").End(xlUp).Row, Range("E65536").End(xlUp).Row)

    With ActiveSheet
    For i = lRow To 2 Step -1
    If .Cells(i, "C").Value = "All values USD Millions." Then
      Range("C" & i & ":H" & i).ClearContents
    End If
   Next i
   End With


   End Sub