简体   繁体   中英

Excel macro for copying cell contents to a specific sheet in another workbook

What I need is a way to send the contents of some cells in "ThisWorkbook" (where the macro is) to a specific sheet in another workbook (the location of which will not change, unlike "ThisWorkbook")

for some reason, this below dosen't work:

Sub Transplant()

Dim thispath As String
Dim targetpath As String

'Set filepaths
thispath = ThisWorkbook.FullName
targetpath = ThisWorkbook.Path & "/subdir/Targetbook.xlsm"



Dim Srcwb As Workbook
Dim Trgwb As Workbook

'Set workbooks
Set Srcwb = Workbooks.Open(thispath)
Set Trgwb = Workbooks.Open(targetpath)

Srcwb.Worksheets("Sheet1").Range(Srcwb .Worksheets("Sheet1").Range("A1"), _
Srcwb.Worksheets("Sheet1").Range("A1").End(xlToRight)).Copy _
Destination:=Trgwb.Sheets("Sheet1").Cells(1, 1)


End Sub

Please help!

//Leo

This is pretty much the same as what you've got, although I didnt re-open the active workbook.

Can you describe the range you're trying to copy? You might find that UsedRange is easier.

Sub Transplant()
    Dim DWB As Workbook
    Dim S As Worksheet
    Set S = ThisWorkbook.WorksheetS("Sheet1") ' forgot to rename Source to S

    Set DWB = Application.Workbooks.Open(Thisworkbook.Path & "/subdir/Targetbook.xlsm")
    Set D = DWB.Worksheets("Sheet1")

    S.Range(S.Range("A1"), S.Range("A1").End(xlToRight)).Copy Destination:=D.Cells(1,1)
    ' S.UsedRange.Copy Destination:=D.Cells(1,1) - this might be easier
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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