简体   繁体   中英

How do i set copy and paste destination?

My goal is to copy and paste from one workbook to another, but I want to have dynamic names - now are statitic and declared in code.

From the code below is visible how it is set now. How can i change my code so these names will be automatic based on the cell (eg.: destination now is "ToThere.xslx" to a value that is in a cell "O2")

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
Dim Name as Short
 Name = Range("O2").Value

 'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("FromHere.xlsm").Worksheets("List1")

 ' I would like this part here to be: Workbooks(Name).Worksheets("List1")
  Set wsDest = Workbooks("ToThere.xlsx").Worksheets("List1")

 '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

'2. Find first blank row in the destination range based on data in 
  column A
  'Offset property moves down 1 row
   lDestLastRow = wsDest.Cells(wsDest.Rows.Count, 
  "A").End(xlUp).Offset(1).Row

 '3. Copy & Paste Data
   wsCopy.Range("A2:H" & lCopyLastRow).Copy _
   wsDest.Range("A" & lDestLastRow)

Here's your example

Sub test()
    Dim wsCopy As Worksheet
    Dim wsDest As Worksheet
    Dim lCopyLastRow As Long
    Dim lDestLastRow As Long
    Dim Name As Integer
    
     Name = Range("O2").Value
    
     'Set variables for copy and destination sheets
      Set wsCopy = Workbooks("FromHere.xlsm").Worksheets("List1")
    
     ' I would like this part here to be: Workbooks(Name).Worksheets("List1")
      Set wsDest = Workbooks("ToThere.xlsx").Worksheets("List1")
    
     '1. Find last used row in the copy range based on data in column A
      lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
    
    '2. Find first blank row in the destination range based on data in
      'Column A
      'Offset property moves down 1 row
       lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row
    
     '3. Copy & Paste Data
       wsCopy.Range("A2:H" & lCopyLastRow).Copy
       ActiveSheet.Paste Destination:=wsDest.Range("A" & lDestLastRow)
    
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