我需要帮助创建一个宏,当它站在单元格A中时,它会删除我在下面标记为X的单元格中的值(将单元格标记为O)。实际单元格可以包含任何值。
A X X X
X O X X
X X O X
X X X O
这可能吗?
答案 0 :(得分:4)
试试这段代码:
Sub go_sub()
Dim tmpRNG As Range
Set tmpRNG = ActiveCell.CurrentRegion 'or you could set other range definition here, like Range("A1:d4")
Dim cell As Range
For Each cell In tmpRNG
If cell.Row <> cell.Column Then cell.ClearContents
Next cell
End Sub
编辑上面的代码适用于从单元格A1开始的当前区域。
以下代码适用于任何选定的区域:
Sub go_sub()
Dim tmpRNG As Range
Set tmpRNG = Selection
Dim tmpOff As Long
tmpOff = tmpRNG.Row - tmpRNG.Column
Dim cell As Range
For Each cell In tmpRNG '.Cells
If cell.Row - tmpOff <> cell.Column Then cell.ClearContents
Next cell
End Sub
一个提示:如果你有一个大的,可以使用关闭屏幕更新,也可能关闭事件。
答案 1 :(得分:2)
以下将取出您当前的单元格并删除除对角线以外的所有单元格,选择左上角的单元格并保留所有对角线...但我喜欢KazJaw的答案。
Sub go_sub()
'get the range from current cell to the end
Lastrow = ActiveSheet.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastcol = ActiveSheet.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column
Set myRange = ActiveSheet.Range(Selection, ActiveSheet.Cells(Lastrow, Lastcol))
'set the next cell to keep as current one
Set Nextcell = selection
'cycle throug all cells in the range
For Each cel In myRange
'if the cell is to be kept?
if cel.address = nextcell.address then
'Reset the next cell to save BUT DONE CLEAR THECURRENT CELL
set Nextcell = Nextcell.offset(1,1)
Else
'clear current cell if not to be saved
Cel.clearcontents
End if
Next
End Sub
<强>之前:强>
<强>后:强>