I am trying to use VBA to ask someone to select an Excel file and, if the file meets the criteria, I want to output certain columns to a new workbook.
I started by creating the script that allows the user select a file and then just tried testing if I could see some data output but I am at a loss. My logic seems way off! I have provided the code below. It may not seem to make much sense but, before I derailed, my idea was:
- User opens Excel file (which the macro is within)
- When the script is run, the browse panel opens to select an Excel file
- If that Excel file (workbook) contains the string in cell 8 (also looping through), then output the range of columns in a new workbook.
Here's the code:
Sub Import2()
Dim Input_Workbook As Workbook
Dim Output_Workbook As Workbook
Dim Source_Path As String
Dim LastRow As Long, erow As Long
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Source_Path = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS*), *.XLS*", Title:="Select File To Be Opened")
Set Input_Workbook = Workbooks.Open(Source_Path)
For i = 2 To LastRow
If Cells(i, 8) = "231/8151" Then
Range(Cells(i, 1), Cells(i, 7)).Select
Selection.Copy
Set Output_Workbook = ThisWorkbook
Set Input_Workbook = Workbooks.Open(Source_Path)
Imported_Workbook.Sheets(1).Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Input_Workbook.Cells(erow, 1).Select
Input_Workbook.Paste
Input_Workbook.Save
Input_Workbook.Close
Input_Workbook = False
End If
Output_Workbook.Save
Input_Workbook.Save
Input_Workbook.Close False
Next i
End Sub