VBA实现复制活动行指定列内容粘贴至下方插入新行的方法
VBA实现Excel活动行指定列复制插行方案
基础版:复制活动行A:Z列到下方新行
直接使用以下宏代码即可实现需求:
Sub CopyActiveRowToNewRow() Dim currentRow As Range Dim insertRowIndex As Long ' 定位当前选中单元格所在行 Set currentRow = Selection.Cells(1, 1).EntireRow insertRowIndex = currentRow.Row + 1 ' 关闭屏幕更新减少卡顿 Application.ScreenUpdating = False ' 插入空白新行 Rows(insertRowIndex).Insert Shift:=xlDown ' 仅粘贴A:Z列的单元格值,不带格式、公式 currentRow.Range("A1:Z1").Copy Rows(insertRowIndex).Range("A1").PasteSpecial Paste:=xlPasteValues ' 重置状态 Application.CutCopyMode = False Application.ScreenUpdating = True End Sub
使用步骤
- 按
Alt+F11打开VBA编辑器 - 在左侧工程面板右键点击当前工作簿,选择「插入」-「模块」
- 将代码粘贴到弹出的模块编辑窗口
- 回到Excel界面,选中待复制行的任意单元格,按
Alt+F8选中对应宏名点击执行即可
扩展版:B列双值自动拆分生成两行
如果需要识别B列的两个不同值、自动插入两行并将第二行B列替换为第二个值,可使用以下代码,默认B列的两个值用英文逗号分隔:
Sub SplitBValueAndInsertRows() Dim currentRow As Range Dim insertRowIndex As Long Dim bValue As String Dim bValueList As Variant Set currentRow = Selection.Cells(1, 1).EntireRow bValue = Trim(currentRow.Range("B1").Value) ' 按实际分隔符修改第二个参数,比如用/分隔就改成Split(bValue, "/") bValueList = Split(bValue, ",") Application.ScreenUpdating = False If UBound(bValueList) = 1 Then ' B列存在2个值时插入2行 insertRowIndex = currentRow.Row + 1 Rows(insertRowIndex & ":" & insertRowIndex + 1).Insert Shift:=xlDown ' 第一行粘贴原内容 currentRow.Range("A1:Z1").Copy Rows(insertRowIndex).Range("A1").PasteSpecial Paste:=xlPasteValues ' 第二行粘贴内容后替换B列值 Rows(insertRowIndex + 1).Range("A1").PasteSpecial Paste:=xlPasteValues Rows(insertRowIndex + 1).Range("B1").Value = Trim(bValueList(1)) Else ' B列为单值时仅插入1行粘贴原内容 insertRowIndex = currentRow.Row + 1 Rows(insertRowIndex).Insert Shift:=xlDown currentRow.Range("A1:Z1").Copy Rows(insertRowIndex).Range("A1").PasteSpecial Paste:=xlPasteValues End If Application.CutCopyMode = False Application.ScreenUpdating = True End Sub
注意:如果你的B列双值使用其他分隔符(比如顿号、斜杠、空格),只需要修改
Split函数里的分隔符参数即可适配。
内容的提问来源于stack exchange,提问作者Raj Sekar
相关产品推荐
相关产品推荐

