Excel - 如果单元格A2等于SKU,则清除单元格C2,H2,G2内容

时间:2013-12-05 18:17:29

标签: excel-vba vba excel

请帮我正确格式化这个VBA:

Sub ClearColumns()
Dim lR As Long, Wrds As Variant, vA As Variant, R As Range, i As Long, j As Long
Dim R1 As Range, R2 As Range
lR = Range("A" & Rows.Count).End(xlUp).Row
Wrds = Array("SKU")
Set R = Range("A1:A" & lR)
Set R1 = R.Offset(0, 2).Resize(1, 4)
Set R2 = R.Offset(0, 9).Resize(1, 4)
vA = R.Value
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
For i = LBound(vA, 1) To UBound(vA, 1)
For j = LBound(Wrds) To UBound(Wrds)
    If vA(i, 1) = Wrds(j) Then
        R1.Rows(i).ClearContents
        R2.Rows(i).ClearContents
        Exit For
    End If
Next j
Next i
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub

这就是我要做的事情:

如果A2列中的单元格包含“SKU”,则清除D2,G2,H2,I2,J2,K2,L2,M2,P2,R2,AB2的内容

感谢。

1 个答案:

答案 0 :(得分:0)

这是一种使用Autofilter的方法,通常比循环快得多,Range.SpecialCells属性以及Range.OffsetRange.Resize

Sub DeleteSkuRows()
Dim ws As Excel.Worksheet
Dim rngToClear As Excel.Range

Set ws = ActiveSheet 'change to suit
ws.Range("A1").AutoFilter field:=1, Criteria1:="SKU"
Set rngToClear = ws.AutoFilter.Range.Rows(1).Offset(1)
Set rngToClear = rngToClear.Resize(ws.AutoFilter.Range.Rows.Count - 1, ws.AutoFilter.Range.Columns.Count)
Set rngToClear = Intersect(rngToClear, ws.Range("D:D,G:M,P:P,R:R,AB:AB")).SpecialCells(xlCellTypeVisible)
rngToClear.ClearContents
ws.AutoFilterMode = False
End Sub
相关问题