我有以下代码,它在双击上面想要插入新行的位置后添加一行:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
On Error Resume Next
Target.Offset(1).EntireRow.SpecialCells (xlConstants).ClearContents
End Sub
当您运行,它清除所有内容的整个行.ClearContents。
我希望看到的是,在最终用户双击一行之后,插入一个新行,但它只清除E到R列中的内容,以及t
所以,我试了这个代码:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
On Error Resume Next
Target.Offset(1).EntireRow.SpecialCells (xlConstants)
'need to clear data from columns E through R and column T
Target.Range("E:R").ClearContents
Target.Range("T").ClearContents
End Sub
我认为Target
会拾取行,但除非我定义一个特定的单元格数,否则它不起作用。换句话说,如果我将代码更改为这样,它将工作,但只有(并且总是)清除第10行:
Target.Range("E10:R10").ClearContents
但是行号可能会根据他们双击的位置而变化…但我不知道如何使它动态。
任何帮助都将非常感激!
请尝试此代码:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
Intersect(Target.Offset(1).EntireRow, Range("E:R,T:T")).ClearContents
End Sub
使用Cells
表示法可能更容易。此方法也使用Union
方法。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
On Error Resume Next
Target.Offset(1).EntireRow.SpecialCells (xlConstants)
On Error GoTo 0
'need to clear data from columns E through R and column T
Union(Range(Cells(Target.Row, "E"), Cells(Target.Row, "R")), Cells(Target.Row, "T")).offset(1).ClearContents
End Sub