Adam Warner
Adam Warner

Reputation: 1354

User Open CSV Into Tab Using VBA

I am trying to a button that when pressed prompts the user to open a csv file and then a bunch of other things are automatically performed on the csv file. Here is code that I am currently working with:

Sub MainMacro()

Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv), *.csv", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath

'Sheets.Add After:=Sheets(Sheets.Count)

'ActiveSheet.name = fNameAndPath

Call Macro1
Call Macro2
Call Macro3
Call Macro4
End Sub

Put this opens up the csv file and I want it to open in the tab and so the Marco1 Marco2... can perform their respective tasks. So the button would perform all of MainMacro() on the newly active sheet which the user then loaded in.

Upvotes: 0

Views: 1010

Answers (1)

Dave
Dave

Reputation: 4356

This code will open the csv and then copy the worksheet to your original workbook for you to do with as you will. On copying the sheet to the destination workbook, the copied sheet will also activate.

Sub MainMacro()
    Dim csvWB As Workbook
    Dim fNameAndPath As Variant
    fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv), *.csv", Title:="Select File To Be Opened")
    If fNameAndPath = False Then Exit Sub
    Set csvWB = Workbooks.Open(Filename:=fNameAndPath)
    csvWB.Worksheets(1).Copy Before:=ThisWorkbook.Worksheets(1)
    csvWB.Close
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

Of course, depending on what Macro1-4 actually do, it may be easier to open it in a different workbook and just perform your Macros against that?

Upvotes: 2

Related Questions