如何清除所有数据除了列X,Y和& Z'

时间:2015-07-04 18:28:20

标签: excel vba excel-vba multiple-columns rowdeleting

我想清除所有(不删除)工作表中的内容除了列X,Y和& Z(例如)?这些列存储在变量中。

2 个答案:

答案 0 :(得分:7)

是的,您清除了两个范围:

  • 第1栏(' A')至23(' W')的第1号范围。
  • 第27栏(' AA')中的第2号范围到最后使用的列。

这个功能可以做到:

Public Sub CustomClear()
    Dim ws As Worksheet
    Set ws = ActiveSheet

    ws.Range(ws.Columns(1), ws.Columns(23)).Clear
    ws.Range(ws.Columns(27), ws.Columns(ws.UsedRange.End(xlToRight).Column)).Clear
End Sub

答案 1 :(得分:0)

非常有趣的问题 - @ SQLPolice的回答简明扼要地完成了工作。 (顺便说一下+1)。

这是另一个选项,它可以处理Range以外的列中的Range("X:Z")变量:

Option Explicit
Public Sub ClearRangesBeforeAndAfter()

    Dim rngToKeep As Range, rngToClear As Range
    Dim lngColNum As Long
    Dim wks As Worksheet

    Set wks = ThisWorkbook.Worksheets(1) '<~ assume we're on Sheet1

    With wks
        Set rngToKeep = .Range("W:Z") '<~ this is the example range from OP
        '
        'Or, we could pick any other group of continuous columns, like:
        '
        'Set rngToKeep = .Range("B:D")
        'Set rngToKeep = .Range("H:Z")
        'Set rngToKeep = .Range("A:AZ")

        'First, find the farthest-left border of the "keep" range
        'by leveraging the relative nature of rngToKeep.Cells
        lngColNum = rngToKeep.Cells(1, 1).Column

        'Now we can clear everything up to that border
        If lngColNum > 1 Then
            Set rngToClear = .Range(.Columns(1), .Columns(lngColNum - 1))
            rngToClear.Clear
        End If

        'Then, find the farthest-right border of the "keep" range
        'and clear the remaining cells
        lngColNum = rngToKeep.Offset(0, rngToKeep.Columns.Count).Column
        Set rngToClear = .Range(.Columns(lngColNum), _
                                .Columns(.Columns.Count))
        rngToClear.Clear
    End With

End Sub