[英]How to clear all data EXCEPT columns X, Y & Z?
我想清除工作表中除X,Y和Z列之外的所有(而不是刪除)內容(例如)嗎? 這些列存儲在變量中。
是的,您清除了兩個范圍:
此功能可以做到:
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的答案簡潔地完成了工作。 (順便說一句。)
這是另一個選項,它可以處理在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.