Hello,
I have VBA code which copies information from one spreadsheet to another. The original spreadsheet has many tabs, and when I use the code in it's current form, it throws this error when I try to copy over the columns from a tab that's different to the one that the spreadsheet opens on.
Is it possible to update the code to allow users to select columns from whichever tab.
target_wb.Close
End Sub
I have VBA code which copies information from one spreadsheet to another. The original spreadsheet has many tabs, and when I use the code in it's current form, it throws this error when I try to copy over the columns from a tab that's different to the one that the spreadsheet opens on.
Is it possible to update the code to allow users to select columns from whichever tab.
VBA Code:
Sub copy_data()
Dim data_wb As Workbook
Dim target_wb As Workbook
Dim file_name As Variant
Dim header_range(100) As Range
Dim last_row As Long
Dim col_number As Long
Dim col_letter As String
Dim counter As Long
Dim quantity As Long
'select workbook
file_name = Application.GetOpenFilename(Title:="Choose a target workbook")
If file_name <> False Then
'create a new target workbook
Set target_wb = Application.Workbooks.Add
'open workbook with the data
Set data_wb = Application.Workbooks.Open(file_name)
'get quantity to create loop
quantity = _
InputBox("How many columns do you want to copy?")
'loop
For counter = 1 To quantity
'select header range
Set header_range(counter) = _
Application.InputBox("Select the " & counter & "º column you want to copy", Type:=8)
'get last row and col letter
col_number = header_range(counter).Column
last_row = Cells(Rows.Count, col_number).End(xlUp).Row
col_letter = Split(Cells(1, col_number).Address(True, False), "$")(0)
'copy from data_wb
Range(header_range(counter), Range(col_letter & last_row)).Copy
'paste in target_wb
target_wb.Sheets("Sheet1").Cells(1, counter).PasteSpecial xlPasteValues
Next counter
data_wb.Close
If Not target_wb.Saved Then
If MsgBox("Do you want to save the file?", vbYesNo, "Save?") = vbYes Then
Rows("1:9").Delete
target_wb.Save
End If
End If
End If
target_wb.Close
End Sub