Question

i have tried to copy and paste columns from one worksheet in a workbook to another worksheet and workbook.If i give staticnames of the workbooks,worksheets and the columns then the code is running fine.This is the code i have used.

Dim sourcecolumn As Range, targetcolumn As Range
Set sourcecolumn = Workbooks("Book1.xlsm").Worksheets("sheet1").Columns("A")
Set targetcolumn = Workbooks("Book2.xlsm").Worksheets("sheet2").Columns("B")
sourcecolumn.Copy Destination:=targetcolumn

The problem is i want to give dynamic names for both the source and destination worksheets,workbooks and the columns also....can anybody help?thanks in advance

Was it helpful?

Solution

Try something like this:

Sub test()
   Dim thisWB As Workbook, wb1 As Workbook, wb2 As Workbook
   Dim rng1 As Range, rng2 As Range
   Dim tmp1, tmp2

   On Error GoTo errorHandler

   'your current Workbook'
   Set thisWB = ThisWorkbook

   'select first file'
   tmp1 = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", 1, "Choose file #1")
   If tmp1 = False Then Exit Sub  ' File not choosen'

   'open first file for selecting range to copy'
   Workbooks.Open Filename:=tmp1, ReadOnly:=True
   Set wb1 = ActiveWorkbook

   'select range to copy (you can select entire row or column)'
   Set rng1 = Application.InputBox(Prompt:="Please Select Range to copy", Title:="Range Select", Type:=8)

   'select second file'
   tmp2 = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", 1, "Choose file #2")
   If tmp2 = False Then ' File not choosen'
       wb1.Close
       Exit Sub
   End If

   'open second file for selecting range where to paste'
   If tmp1 = tmp2 Then
       Set wb2 = wb1
   Else
       Workbooks.Open Filename:=tmp2
       Set wb2 = ActiveWorkbook
   End If

   'select range where you need paste values'
   Set rng2 = Application.InputBox(Prompt:="Please Select Range where to paste", Title:="Range Select", Type:=8)

   rng1.Copy Destination:=rng2

   'close workbooks'
   wb1.Close
   If tmp1 <> tmp2 Then wb2.Close
   Exit Sub

'Error handler'
errorHandler:
   MsgBox Err.Description, vbCritical, "Error!"
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top