VBA Copy / paste values from one workbook to anoth

2019-09-14 18:52发布

I have two workbooks the first one is called classeur1 and the second is called classeur2.

I cannot copy / paste merged rows from a table from Sheet1 (from Workbook1) to Sheet2 (from Workbook2).

I would like to know how to do it.

In fact I tried but no result. Here is my code:

Sub test()
    Dim finalrow As Long
    Workbooks("workbook1").Worksheets("sheet1").Range("D1:D" & finalrow).Value = Workbooks("workbook2").Worksheets("sheet2").Range("A2:A" & finalrow).Value
End Sub

标签: excel vba
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-14 19:05

You can try to define the name for your table by selecting the range, and Insert -> Tables -> Table. Let's say the name is "Table1"

Option Explicit

Sub CopyTable()
'Select the defined Table1 from classeur1 workbook and copy it to classeur2 starting at cell D1

Workbooks("classeur1").Worksheets("Sheet1").Range("Table1[#All]").Copy _ 
    Workbooks("classeur2").Worksheets("Sheet1").Range("D1")
End Sub
查看更多
冷血范
3楼-- · 2019-09-14 19:12

One of your ranges starts at D1 and the other at A2 but both go to finalRow. This makes them different size ranges. I'll assume that you have actually assigned a row number to finalRow but I won't use it.

Option Explicit

Sub test()
    With Workbooks("Classeur2").Worksheets("Feuil2")
        With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp))
            Workbooks("Classeur1").Worksheets("Feuil1").Range("D1").Resize(.Rows.Count, .Columns.Count) = .Value
        End With
    End With
End Sub
查看更多
登录 后发表回答