Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet, wsO As Worksheet
Dim i As Integer
Dim lColumn As Long
Dim a, c, var, counter, column_name, strsearch, column_arr As Variant
Dim rU As Range
Set c = CreateObject("scripting.dictionary")
Set a = CreateObject("scripting.dictionary")
column_arr_1 = Array("X1", "Y2")
column_arr_2 = Array("Z3", "A1")
column_arr_3 = Array("B1", "C1")
column_arr = Array(column_arr_1, column_arr_2, column_arr_3)
For i = 1 To (UBound(column_arr) - LBound(column_arr) + 1)
a.Add i, column_arr(i - 1)
Next i
Filepath = "C:\Users\tejas\Desktop\Test"
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1")
lColumn = wsI.Cells(1, Columns.Count).End(xlToLeft).Column
wsI.Rows(1).Replace What:=" ", Replacement:=""
'MsgBox ("I am before For")
For counter = 0 To 2
'MsgBox ("I am inside For")
Set wbO = Workbooks.Add
Set wsO = wbO.Sheets("Sheet1")
wbO.SaveAs Filename:=Filepath & Str(a.Keys()(counter)) & "_Result.xlsx"
For Each strsearch In a.Items()(counter)
Set column_name = wsI.Rows(1).Find(What:=strsearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
MsgBox (column_name.Column)
If column_name Is Nothing Then
MsgBox (strsearch & " Not Found")
Else
c.Add strsearch, column_name.Column
End If
Next strsearch
Set rU = Nothing
For var = 0 To c.Count - 1
If rU Is Nothing Then
Set rU = wsI.Columns(Int(c.Items()(var)))
Else
Set rU = Union(rU, wsI.Columns(Int(c.Items()(var))))
End If
Next var
rU.Copy
'MsgBox (rU.Count)
wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
wbO.Save
wbO.Close
c.RemoveAll
Next counter
End Sub