0

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

4

2 回答 2

8

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

  • 从第 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
于 2015-07-04T18:44:20.503 回答
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
于 2015-07-06T04:20:15.317 回答