[英]How to clear all data EXCEPT columns X, Y & Z AND rows A,B,C?
我见过这个非常相似的问题,我认为用户@SQL Police 的回答很棒! 但我不知道如何修改或调整它以产生我正在寻找的结果。 这是我的(类似但不同的)问题:
我想删除不在第 24 - 26 列中的所有内容,但也不在第 1 - 6 行中。
我有代码可以单独执行,但不能一起执行。
删除指定列:
Sub ColClear()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Range(ws.Columns(1), ws.Columns(23)).ClearContents
ws.Range(ws.Columns(27), ws.Columns(ws.UsedRange.End(xlToRight).Column)).Clear
End Sub
要删除指定的行:
Sub RowClear()
With Sheets("SheetName")
.Rows(7 & ":" & .Rows.Count).ClearContents
End With
End Sub
但是我怎么能同时做这两个呢? (两个范围的交集,而不是并集)
谢谢!
适应您的要求,基本思想是分别获取双方的范围然后ClearContents
:
Option Explicit
Private Sub Test()
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
Dim bottomLeftRng As Range
Set bottomLeftRng = .Range(.Cells(7, 1), .Cells(.Rows.Count, 23))
Dim bottomRightRng As Range
Set bottomRightRng = .Range(.Cells(7, 27), .Cells(.Rows.Count, .Columns.Count))
End With
bottomLeftRng.ClearContents
bottomRightRng.ClearContents
End Sub
遗憾的是 Excel VBA 对象模型没有提供Difference()
函数来补充包含的Union()
和Intersect()
函数。
如果它做到了,您的任务将像这样简单:
With Difference(ws.[x:z], ws.[1:6])
.ClearContents
End With
因此,让我们创建一个可以使用上述代码段调用的Difference()
函数:
Function Difference(r1 As Range, r2 As Range) As Range
Dim x1&, x2&, x3&, x4&
Dim y1&, y2&, y3&, y4&
Dim a&, rBox As Range, rUni As Range, rInt As Range
Set rInt = Intersect(r1, r2)
Set rUni = Union(r1, r2)
Set rBox = rUni.Areas(1)
For a = 2 To rUni.Areas.Count
Set rBox = Range(rBox, rUni.Areas(a))
Next
x1 = rBox.Column
x2 = rInt.Column - 1
x3 = rInt.Column + rInt.Columns.Count
x4 = rBox.Column + rBox.Columns.Count - 1
y1 = rBox.Row
y2 = rInt.Row - 1
y3 = rInt.Row + rInt.Rows.Count
y4 = rBox.Row + rBox.Rows.Count - 1
Set rUni = Range(Cells(y3, x3), Cells(y4, x4))
If y2 Then Set rUni = Union(rUni, Range(Cells(y1, x3), Cells(y2, x4)))
If x2 Then Set rUni = Union(rUni, Range(Cells(y3, x1), Cells(y4, x2)))
If y2 > 0 And x2 > 0 Then Set rUni = Union(rUni, Range(Cells(y1, x1), Cells(y2, x2)))
Set Difference = rUni
End Function
我相信这解决了保留两个范围的交集和并集内容同时清除其他所有内容的一般情况。
它也适用于较小的范围,仅清除框内紧紧围绕联合的角落区域:
With Difference(ws.[a9:ba11], ws.[v3:z25])
.ClearContents
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.