[英]How to clear all data EXCEPT columns X, Y & Z?
I would like to clear ALL (not delete) the content in a worksheet EXCEPT columns X, Y & Z (for example)? 我想清除工作表中除X,Y和Z列之外的所有(而不是删除)内容(例如)吗? These columns are stored in a variable.
这些列存储在变量中。
Yes, you clear two ranges: 是的,您清除了两个范围:
This function does it: 此功能可以做到:
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
Really interesting question -- and @SQLPolice's answer succinctly gets the job done. 真正有趣的问题-@SQLPolice的答案简洁地完成了工作。 (+1 on that by the way.)
(顺便说一句。)
Here's another option, which can handle Range
variables that start / stop in columns other than Range("X:Z")
: 这是另一个选项,它可以处理在
Range("X:Z")
之外的其他列中开始/停止的Range
变量:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.