Excel VBA突发重叠选区错误,存于模块1的代码需移到工作表吗?
问题结论
不需要将代码从Module1迁移到工作表模块,该报错和代码存放的模块位置无关。
报错根因
"Cannot use that command on overlapping selections" 报错触发于
vrg.Delete Shift:=xlShiftUp执行阶段:
筛选得到的Ask Spread列为空的行如果是不连续的,SpecialCells(xlCellTypeVisible)会返回多块不相交的Range对象,Excel对结构化表的跨区域范围执行批量删除时,会偶发选区重叠判定异常,代码中多余的TradeTable.Select操作也可能干扰选区判定逻辑。
修复方案
优化代码逻辑,去掉冗余操作,改用倒序合并待删区域的方式避免多区域删除异常,优化后代码如下:
Sub Test() Application.DisplayAlerts = False Dim TradeTable As Excel.ListObject Set TradeTable = Sheets("Pre Trade").ListObjects("PreTradeTable") With TradeTable ' 清除历史筛选 If .AutoFilter.FilterMode Then .AutoFilter.ShowAllData ' 筛选目标列为空的行 .Range.AutoFilter Field:=.ListColumns("Ask Spread").Index, Criteria1:="" Dim vrg As Range On Error Resume Next Set vrg = .DataBodyRange.SpecialCells(xlCellTypeVisible) On Error GoTo 0 ' 清除当前筛选 .AutoFilter.ShowAllData If Not vrg Is Nothing Then Dim i As Long, delRng As Range ' 倒序遍历合并待删行,避免删除时行号错位和区域重叠报错 For i = .ListRows.Count To 1 Step -1 If Not Intersect(.ListRows(i).Range, vrg) Is Nothing Then If delRng Is Nothing Then Set delRng = .ListRows(i).Range Else Set delRng = Union(delRng, .ListRows(i).Range) End If End If Next i If Not delRng Is Nothing Then delRng.Delete Shift:=xlShiftUp End If End With Application.DisplayAlerts = True End Sub
额外说明
如果你的表格数据量小于1万行,倒序遍历的性能损耗完全可以忽略,且能彻底避免多区域删除的各类偶发报错。
内容的提问来源于stack exchange,提问作者Motacular
相关产品推荐
相关产品推荐

