3

我对 VBA 编程真的很陌生,并且我尝试编写的这段代码有问题。我希望代码找出 A 列中未使用的第一行,然后将数据从工作表的不同部分复制并粘贴到该行中。

Sub CopyandPaste()


Dim RowLast As Long

RowLast = ThisWorkbook.Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1,   0).Row

Set NewRange = ThisWorkbook.Worksheets("Sheet2").Cells(RowLast, 1)

ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select
Selection.Copy

Range("NewRange").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

End Sub

任何帮助都会非常有帮助。

4

2 回答 2

1

试试这个代码:

Sub CopyandPaste()

    Dim RowLast As Long

    ThisWorkbook.Activate
    With Worksheets("Sheet2")
        RowLast = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
        Sheets("Sheet1").Cells(8, "B").Copy Sheets("Sheet2").Cells(RowLast, 1)
    End With

End Sub
于 2013-05-31T19:11:17.980 回答
1

我在代码中添加了注释来解释我所做的更改。

Sub CopyandPaste()

    Dim RowLast As Long
    Dim newRange As Range

    'this works easier if I understand your intent right
    'I generally use some large row number with Excel 2010
    'You may ahve to make this smaller if you are in 03
    RowLast = Sheets("Sheet2").Range("B99999").End(xlUp) + 1

    'if you KNOW you have continuous data in this column (no spaces)
    RowLast = Sheets("Sheet2").Range("B1").End(xldown) + 1

    'this is slightly better way to do this
    Set newRange = ThisWorkbook.Worksheets("Sheet2").Range("A" & RowLast)

    'don't do this
    'ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select
    'Selection.Copy

    'do this instead
    Sheets("Sheet1").Range("B8").Copy
    newRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

    'you were attempting to use a variable name (newrange) as a
    'name of a named range in the Excel sheet
    'use the variable range itself (as above)

End Sub
于 2013-05-31T19:13:51.947 回答