我想清除除X,Y&Z列(例如)以外的工作表中的所有内容(而不是删除)。这些列存储在一个变量中。
发布于 2015-07-04 18:44:20
是的,您清除了两个范围:
这个职能是这样做的:
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-06 04:20:15
非常有趣的问题-- @ Really的回答简明扼要地完成了任务。(顺便说一句)
下面是另一个选项,它可以处理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 Subhttps://stackoverflow.com/questions/31223920
复制相似问题