我有相当多的Excel数据库。大约一半的列数据是手工输入的。有一个问题已经困扰我一段时间了。我手动插入行。我手抄公式。非常容易出错。我手动设置了格式。这张纸相当复杂。
我试着自动化这个过程,可惜总是有这样那样的错误。
Sub InsertRow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
End Sub
这似乎没有复制公式。以及如何在特定列中放置默认值?
感谢所有的帮助。
发布于 2020-10-30 10:09:32
这里有一个你的问题的解决方案。在要插入行的工作表的代码模块中安装代码。它是工作簿中预先存在的模块之一,以选项卡命名。如果希望在多个工作表上执行相同的操作,请在每个适用的代码模块中安装该过程的一个版本。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Const TriggerClm As String = "A" ' change to suit
Const FirstDataRow As Long = 2 ' change to suit
Dim Rng As Range
Set Rng = Cells(Rows.Count, TriggerClm).End(xlUp).Offset(1)
With Target
If (.Address = Rng.Address) And (.Row > FirstDataRow) Then
Rows(.Row - 1).Copy ' copies from last used row
' Rows(FirstDataRow).Copy ' copies from FirstDataRow
Rows(.Row).Insert Shift:=xlDown
On Error Resume Next
Rows(.Row - 1).SpecialCells(xlCellTypeConstants).ClearContents
Application.CutCopyMode = False
Cancel = True
End If
End With
End Sub
这就是将要发生的事情。当您双击单元格时,代码模块会捕获,上面的过程会对该操作做出响应。如果双击位于A列(TriggerClm)中最后使用的单元格下方的空单元格上,则会在该位置插入一个空行。它将包含从工作表的上一行或第一行复制的所有格式和公式(FirstDataRow)。
这也定义了所需的设置。您可以指定"A“以外的TriggerClm和2以外的FirstDataRow。您必须在两个源之间进行选择,禁用您不想使用的源。请阅读代码中的备注。
在多年的动摇之后,我现在更喜欢我大多数项目中最后使用的行而不是第一行。如果需要的话,我通常还会添加代码来插入日期,通常是在TriggerClm中。
您可能对双击切换到单元格内编辑的原始功能很熟悉。插入行时取消此功能。但是,如果您删除Cancel = True
,那么代码将在新单元格中的编辑模式中停止。
发布于 2020-10-30 10:17:41
如果您想将它作为宏保留在模块中,下面是代码。并不是说,当excel复制“公式”时,它也会复制值。我还添加了一个留置权,向您展示如何将第3列更改为第5列
Sub InsertRow()
Dim CurRow As Range
Dim NewRow As Range
ActiveCell.EntireRow.Insert
Set CurRow = ActiveCell.EntireRow.Offset(1)
Set NewRow = ActiveCell.EntireRow
CurRow.Copy
NewRow.PasteSpecial Paste:=xlPasteFormulas
NewRow.PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
NewRow.Columns(3) = 5
End Sub
https://stackoverflow.com/questions/64601326
复制相似问题