Choose and select files to import instead of hardcoded file folder

Berenloper

Board Regular
Joined
May 28, 2009
Messages
83
Office Version
  1. 365
Platform
  1. Windows
Hi everyone,

I have a working macro for import of csv files where they are presented on different worksheets. In the macro the directory where the csv files are is hardcoded ("fs.GetFolder="). This is the working code:

Code:
Dim fs As New FileSystemObject
Dim fo As Folder
Dim fi As File
Dim WB As Workbook
Dim Ws As Worksheet
Dim sname As String

Sub ImportCSV()
Application.ScreenUpdating = False
    Set WB = ThisWorkbook
    Set fo = fs.GetFolder("C:\Users\berenloper\Downloads\CSV\")
    For Each fi In fo.Files
        If UCase(Right(fi.Name, 4)) = ".CSV" Then
            sname = Replace(Replace(fi.Name, ":", "_"), "\", "-")
            Set Ws = WB.Sheets.Add
            sname = Split(fi.Name, ".")(0) 'credit to [URL="https://www.mrexcel.com/forum/excel-questions/1019322-create-sheetnames-based-imported-filenames-without-extension.html?highlight=berenloper"]Matt Mickle[/URL]
            Ws.Name = sname
            Call WizardTexfileImport(fi.Path, Ws)
        End If
    Next
    
    For I = 1 To Application.Sheets.Count
    For j = 1 To Application.Sheets.Count - 1
            If UCase$(Application.Sheets(j).Name) > UCase$(Application.Sheets(j + 1).Name) Then
                Sheets(j).Move After:=Sheets(j + 1)
            End If
    Next
    Next
Application.ScreenUpdating = True
End Sub

Sub WizardTexfileImport(what As String, where As Worksheet)
With Ws.QueryTables.Add(Connection:= _
    "TEXT;" & what, Destination:=Range("$A$4"))
    .Name = "test1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
End Sub
The question I have is: "Is it possible to change this so I can choose where and which csv files I want to import?"
I found other code which uses "Application.GetOpenFilename" so I tried the following. But as I have little knowledge of programming it sadly faild.

Code:
Dim fs As New FileSystemObject
Dim fo As Folder
Dim fi As File
Dim WB As Workbook
Dim Ws As Worksheet
Dim sname As String
Dim xFilesToOpen As Variant

Sub ImportCSV()
Application.ScreenUpdating = False
xFilesToOpen = Application.GetOpenFilename("Text Files (*.csv), *.xls", , "Import csv", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files selected", , "Import csv"
        GoTo ExitHandler
    End If
    Set WB = ThisWorkbook
    'Set fo = fs.GetFolder("C:\Users\berenloper\Downloads\CSV\")
    Set fo = xFilesToOpen
    For Each fi In fo
        If UCase(Right(fi.Name, 4)) = ".CSV" Then
            sname = Replace(Replace(fi.Name, ":", "_"), "\", "-")
            Set Ws = WB.Sheets.Add
            sname = Split(fi.Name, ".")(0) 'credit to [URL="https://www.mrexcel.com/forum/excel-questions/1019322-create-sheetnames-based-imported-filenames-without-extension.html?highlight=berenloper"]Matt Mickle[/URL]
            Ws.Name = sname
            Call WizardTextfileImport(fi.Path, Ws)
        End If
    Next
    
    For I = 1 To Application.Sheets.Count
    For j = 1 To Application.Sheets.Count - 1
            If UCase$(Application.Sheets(j).Name) > UCase$(Application.Sheets(j + 1).Name) Then
                Sheets(j).Move After:=Sheets(j + 1)
            End If
    Next
    Next
ExitHandler:
    Application.ScreenUpdating = xScreen
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Import csv"
    Resume ExitHandler
Application.ScreenUpdating = True
End Sub

Sub WizardTexfileImport(what As String, where As Worksheet)
With Ws.QueryTables.Add(Connection:= _
    "TEXT;" & what, Destination:=Range("$A$4"))
    .Name = "test1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
End Sub
Any help on this would again be appreciated!

Regards,

Berenloper
 
Hold on John. I found the problem I think.

Very weird. When copying the code from this board into my editor, the back slash as spoken before disappeares... :eeek:
Saw it accidental when viewing this thread on my tablet. Never seen this behaviour before. I will test later!

Regards,

Berenloper
 
Upvote 0

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
Hello John,

Yes! Finally success :biggrin:
It took me some more puzzling (in the second sub) before I got it working. The missing backslash is something I can't explain. Perhaps someone else knows the reason for this, but it's good to know.

Thanks for your help John. I appreciate it!

Here's the complete code for anyone interested:

Code:
Sub ImportCSV()
    Dim fi As Variant
    Dim Ws As Worksheet
    Dim sname As String
    Dim xFilesToOpen As Variant
    
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.csv), *.xls", , "Import csv", , True)

    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files selected", , "Import csv"
        Exit Sub
    End If

    Application.ScreenUpdating = False

    For Each fi In xFilesToOpen
        If UCase(Right(fi, 4)) = ".CSV" Then
            sname = Mid(fi, InStrRev(fi, "\") + 1)
            sname = Left(sname, InStrRev(sname, ".") - 1)
            Set Ws = ThisWorkbook.Sheets.Add
            Ws.Name = sname
            Call WizardTextfilesImport(CStr(fi), Ws)
        End If
    Next

'Sorting of sheets...

        For I = 1 To Application.Sheets.Count
        For j = 1 To Application.Sheets.Count - 1
                If UCase$(Application.Sheets(j).Name) > UCase$(Application.Sheets(j + 1).Name) Then
                    Sheets(j).Move After:=Sheets(j + 1)
                End If
        Next
        Next

    Application.ScreenUpdating = True

ExitHandler:
    Application.ScreenUpdating = xScreen
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Import csv"
    Resume ExitHandler

End Sub

Sub WizardTextfilesImport(what As String, Ws As Worksheet)
With Ws.QueryTables.Add(Connection:= _
    "TEXT;" & what, Destination:=Range("$A$4"))
    .Name = "test1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
End Sub
Regards,

Berenloper
 
Upvote 0
Solution

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top