如何清除 X、Y 和 Z 列以外的所有数据?
How to clear all data EXCEPT columns X, Y & Z?
我想清除(而不是删除)工作表中除 X、Y 和 Z 列之外的所有内容(例如)?这些列存储在一个变量中。
是的,你清除了两个范围:
- 从第 1 列 ('A') 到 23 ('W') 的第 1 个范围。
- 第 2 列从第 27 列('AA')到最后使用的列。
这个函数做到了:
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
非常有趣的问题——@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
我想清除(而不是删除)工作表中除 X、Y 和 Z 列之外的所有内容(例如)?这些列存储在一个变量中。
是的,你清除了两个范围:
- 从第 1 列 ('A') 到 23 ('W') 的第 1 个范围。
- 第 2 列从第 27 列('AA')到最后使用的列。
这个函数做到了:
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
非常有趣的问题——@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