我尝试创建一个命令按钮,以基于ActiveCell清除多张纸上的某些单元格。
例如我选择了单元格A1,那么命令按钮应该: -清除A1旁边的第1个单元格(A2),第3个单元格(A4)和第5个单元格(A6)的内容。和其他工作表的原理相同,但单元格不同。
到目前为止,我只设法清除了当前工作表中的单元格。
Private Sub CommandButton1_Click()
ActiveCell.Offset(0, 1).ClearContents
ActiveCell.Offset(0, 2).ClearContents
ActiveCell.Offset(0, 3).ClearContents
ActiveCell.Offset(0, 6).ClearContents
ActiveCell.Offset(0, 7).ClearContents
ActiveCell.Offset(0, 8).ClearContents
End Sub
基本上,如果我在工作表1中选择了A1并按命令按钮,则应该对工作表2和3等执行上面的代码和相同的代码,但坐标不同。
答案 0 :(得分:0)
要清除工作簿中所有工作表上的单元格,您将需要遍历每张工作表。以下内容将循环浏览每个工作表,并清除与Offset
Activecell
单元格的内容
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim coords As Object
Dim j, key
Set coords = CreateObject("scripting.dictionary")
With coords
.Add key:="Sheet1", Item:=Array(1, 3, 6, 7, 8)
'.Add Key:="Sheet2", Item:=Array(2, 3, 6, 7, 9)
' ... etc.
End With
For Each key In coords
Set ws = Nothing
On Error Resume Next
Set ws = ThisWorkbook.Sheets(key)
On Error GoTo 0
If Not ws Is Nothing Then
With ws.Range(ActiveCell.Address)
For Each j In coords.Item(key)
.Offset(0, j).ClearContents
Next j
End With
End If
Next key
End Sub
答案 1 :(得分:0)
您可以尝试:
Option Explicit
Sub test()
Dim Row As Long, Column As Long
Dim ws As Worksheet
Column = ActiveCell.Column
Row = ActiveCell.Row
For Each ws In ThisWorkbook.Worksheets
With ws
.Cells(Row + 1, Column).ClearContents
.Cells(Row + 3, Column).ClearContents
.Cells(Row + 5, Column).ClearContents
End With
Next ws
End Sub