在另一个工作簿中添加一行时复制单元格

时间:2017-02-16 16:13:45

标签: excel vba excel-vba

所以我必须从一个工作簿中复制单元格A1,B2和C3,并在另一个工作簿中添加一行(在最后一行),并在A,B,C列中添加这些值。

这是我到目前为止所得到的,我认为我很接近,但我无法完成。 我不知道这句话是什么错误“设置lastrow = wNew.Cells。(Rows.Count,”A“)。结束(xlUp).Row + 1”认为是问题

Sub Botão1_Clique()

Dim wks As Worksheet
Dim wNew As Worksheet
Dim y As Workbook
Dim lastrow As Long

Application.ScreenUpdating = False
Set wks = ActiveSheet

Set y = Workbooks.Open("Y:\teste.xlsx")

Set wNew = y.Sheets("GERAL")

Set lastrow = wNew.Cells.(Rows.Count, "A").End(xlUp).Row + 1


wks.Cells(1, 1).Copy
wNew.Cells(lastrow, 1).PasteSpecial Paste:=xlPasteValues
wks.Cells(2, 2).Copy
wNew.Cells(lastrow, 2).PasteSpecial Paste:=xlPasteValues
wks.Cells(3, 3).Copy
wNew.Cells(lastrow, 3).PasteSpecial Paste:=xlPasteValues



  Application.ScreenUpdating = True


End Sub

我还想关闭Y:\ teste.xlsx工作簿,并显示一条消息“ROW ADDED”

1 个答案:

答案 0 :(得分:0)

您可以很好地引用WorkbooksWorksheets,但也要确保完全符合CellsRows的要求。它们是工作表对象的属性。 ThisWorkbook.Worksheets("..").Rows

Sub Botão1_Clique()
    Dim wks As Worksheet, wNew As Worksheet
    Dim y As Workbook
    Dim lastrow As Long

    Application.ScreenUpdating = False

    Set wks = ActiveSheet
    Set y = Workbooks.Open("Y:\teste.xlsx")
    Set wNew = y.Sheets("GERAL")

    With wNew
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
        .Cells(lastrow, 1).Value = wks.Cells(1, 1)
        .Cells(lastrow, 2).Value = wks.Cells(2, 2)
        .Cells(lastrow, 3).Value = wks.Cells(3, 3)
    End With

    'extra code as requested        
    y.Close True 'save changes if TRUE
    MsgBox "ROW ADDED"

    Application.ScreenUpdating = True
End Sub