Excel VBA copy paste columns using public variables as column names
I'm working on a VBA project in Excel, and I'm trying to copy columns from one sheet and paste them to another sheet. I'm using a public variable from a userform with a listbox to ask the user for the name of the column in sheet 1 which correlates with the name of the column in sheet 2. I have to use a listbox because the columns names in sheet 1 can vary slightly depending on the data the user imports.
The public variable is declared at the top of my module using:
Public PartsDeptLBValue As String
I want to copy the data from column name seleted from a sheet named "ImportData" with the data starting on row 5 to a sheet name "PAD2", Column("Parts Description") which starts on row 2.
I've got the userform working correctly, and it's storing the value the user selects in a public variable on the module called PartsDeptLBValue thanks to another expert.
EDIT: I've also tried this code, which I think get's me closer, but I'm getting an error that say's "The information cannot be pasted because the Copy area and the paste area are not the same size and shape."
Sub CopyPasteColumns()Dim t As RangePartsDeptUserForm.Show'Find PartsDeptLBValue in Row 4 With Sheets("ImportData").Rows(4) Set t = .Find(PartsDeptLBValue, lookat:=xlPart)'If found, copy the column to PAD2, Column A'If not found, present a message If Not t Is Nothing Then Columns(t.Column).EntireColumn.Copy _ Destination:=Worksheets("PAD2").Range("A2") Else: MsgBox "Title Not Found" End If End WithEnd Sub
Here's the other code I tried, but I'm getting "Unable to get the Match property of the WorksheetFunction class" error:
Sub CopyPasteColumns()Dim desc As StringPartsDeptUserForm.Show Sheets("ImportData").Select desc = WorksheetFunction.Match( PartsDeptLBValue, Rows("1:1"), 0) Sheets("ImportData").Columns(desc).Copy Destination:=Sheets("PAD2").Range("A2")End Sub