简体   繁体   English

使用VBA自动复制和粘贴整行(excel)

[英]Copy & Paste whole line automatically with VBA (excel)

Sheets("Source").Select
Rows("1:1").Select
Selection.Copy
Sheets("Print").Select
Rows("1:1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Sheets("Source").Select
Rows("2:2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Print").Select
Rows("1:1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

So, this is the sample code. 因此,这是示例代码。 What I want to do is Copy each line from Source Sheet and Paste to 1:1 rows in Print Sheet automatically. 我要做的是自动将每行从“ Source图纸”复制并粘贴到“ Print图纸”中的1:1行。

The range is different every time. 每次范围都不同。 It'll be great if the code works as rows number. 如果代码用作行号,那就太好了。

[2nd question] Alright, Now I got new problem. [第二个问题]好的,现在我遇到了新问题。 After I execute the code, Excel freeze. 执行代码后,Excel冻结。

here's the new code. 这是新代码。

Dim i As Long 'i - Number of rows in Source list
NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
For i = 1 To NumRows
    Worksheets("Source").Rows(i).Copy
    Worksheets("Print").Rows("1:1").PasteSpecial Paste:=xlPasteValues
    Worksheets("Print").PrintOut Copies:=1, Collate:=True, _
            IgnorePrintAreas:=False
Next

You can use a FOR loop sequence but i'm not sure of what you want with the program. 您可以使用FOR循环序列,但是我不确定您想要的程序是什么。 Can you please share some more details about it? 您能否分享一些更多细节?

If i understand you correct, you must use construction like this: 如果我理解正确,则必须使用如下构造:

Dim i as long 'i - Number of rows in Source list
i = 100 'for example
Worksheets("Source").Rows("1:" & i).Copy 
Worksheets("Print").Rows("1:1").PasteSpecial Paste:=xlPasteValues

Let us assume that Source sheet structure like the image below: 让我们假设“ 源工作表”结构如下图所示:

在此处输入图片说明

and Print sheet is empty. 并且打印纸为空。

you could try: 您可以尝试:

Option Explicit

Sub test()

    Dim wsSource As Worksheet, wsPrint As Worksheet
    Dim rngCopy As Range
    Dim LastRow As Long, LastColumn As Long

    Set wsSource = ThisWorkbook.Worksheets("Source")
    Set wsPrint = ThisWorkbook.Worksheets("Print")

    With wsSource

        'Find last row of column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Find last column or row 1
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        'Set range to copy
        Set rngCopy = .Range(.Cells(2, 1), .Cells(LastRow, LastColumn))

    End With

    rngCopy.Copy wsPrint.Range("A1")

End Sub

Result: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM