如何在Excel中多次複製和插入行或將行復制X次?


如果我們想手動複製Excel表格中現有的行,那將是一個耗時的過程,因為我們需要插入並複製值。我們可以使用VBA應用程式來自動化此過程。

閱讀本教程,瞭解如何多次複製和插入一行,或在Excel中將一行復制“X”次。在這裡,我們將首先插入VBA模組,然後執行程式碼以完成任務。讓我們看一下在Excel中多次複製和插入一行或將一行復制“X”次的簡單步驟。

步驟1

讓我們考慮一個Excel工作表,其中包含如下所示的表格。

要開啟VBA應用程式,請單擊“插入”,選擇“檢視程式碼”,單擊“插入”,選擇“模組”,然後將下面提到的程式1鍵入文字框中,如下圖所示。

程式1

Sub test()
'Update By Nirmal
    Dim xCount As Integer
LableNumber:
    xCount = Application.InputBox("Number of Rows", "Duplicate the rows", , , , , , 1)
    If xCount < 1 Then
        MsgBox "the entered number of rows is error, please enter again", vbInformation, "Select the values"
        GoTo LableNumber
    End If
    ActiveCell.EntireRow.Copy
    Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(xCount, 0)).EntireRow.Insert Shift:=xlDown
    Application.CutCopyMode = False
End Sub

步驟2

現在將工作表另存為宏啟用工作表,單擊要複製的值,然後單擊F5,選擇要複製的次數,然後單擊“確定”。

如果我們想複製整行,可以使用程式2代替程式1。

程式2

Sub insertrows()
'Update By Nirmal
Dim I As Long
Dim xCount As Integer
LableNumber:
xCount = Application.InputBox("Number of Rows", "Duplicate whole values", , , , , , 1)
If xCount < 1 Then
MsgBox "the entered number of rows is error ,please enter again", vbInformation, "Enter no of times"
GoTo LableNumber
End If
For I = Range("A" & Rows.CountLarge).End(xlUp).Row To 2 Step -1
Rows(I).Copy
Rows(I).Resize(xCount).Insert
Next
Application.CutCopyMode = False
End Sub

結論

在本教程中,我們使用了一個簡單的示例來演示如何在Excel中多次複製和貼上行或列。

更新於:2023年3月7日

17K+瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.