我有一行,其中有公式使用同一行的值。 下一行是空的,只是背景颜色不同。
现在,如果我插入一个新行(右键单击空行并“插入”),我会得到一个没有背景颜色的新行(这是我想要的),但该行也不包含任何公式:在创建新行时,如何让Excel变得更聪明并从上一行复制公式?
还有一条信息:插入新行时会复制数据验证信息(即下拉列表)。
感谢。
答案 0 :(得分:22)
将包含数据和公式的区域设为表格:
然后在下一行添加新信息将复制该表中新行的所有公式。数据验证也将应用于整个列的新行。这确实是Excel对您的数据更加智能。
无需VBA ......
答案 1 :(得分:2)
您需要插入新行,然后从源行复制到新插入的行。 Excel允许您粘贴特殊的公式。所以在Excel中:
如果需要VBA,行(“1:1”)为源,行(“2:2”)为目标:
Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Clear
Rows("1:1").Copy
Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
答案 2 :(得分:2)
我发现有关在表中复制行的另一个关键因素是,您正在处理的工作表需要激活。 如果您有一个包含多个工作表的工作簿,则需要保存从中调用宏的工作表,然后使用该表激活工作表。 完成后,您可以重新激活原始工作表。
您可以使用Application.ScreenUpdating = False来确保用户没有看到您在宏中切换工作表。
如果您没有激活工作表,副本似乎无法正常工作,即某些东西似乎有效,而其他东西不起作用?
答案 3 :(得分:0)
如果你的工作表有很多行都包含公式,到目前为止最简单的方法是复制一个没有数据的行(但它确实包含公式),然后"插入复制的单元格&#34 ;在您要添加的行的下方/上方。公式仍然存在。在紧要关头,可以使用带数据的行。只需清除它或在粘贴后覆盖它。
答案 4 :(得分:0)
Private Sub Worksheet_Change(按目标的ByVal目标)
'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then
On Error GoTo ERROR_OCCURRED
'unprotect the sheet - otherwise can't copy and paste
ActiveSheet.Unprotect
'disable events - this prevents this routine from triggering again when
'copy and paste below changes the cell values
Application.EnableEvents = False
'copy col D (with validation list) from row above to new row (not locked)
Range("D" & Target.Row - 1).Copy
Range("D" & Target.Row).PasteSpecial
'copy col M to P (with formulas) from row above to new row
Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
Range("M" & Target.Row).PasteSpecial
'确保(是否发生错误)事件重新启用并重新保护工作表
ERROR_OCCURRED:
If Err.Number <> 0 Then
MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
Err.Number & " - " & Err.Description
End If
're-enable events
Application.EnableEvents = True
're-protect the sheet
ActiveSheet.Protect
'put focus back on the next cell after routine was triggered
Range("D" & Target.Row).Select
End If
结束子