Importing .csv with VBA

alsdkjfladjfgj12321

New Member
Joined
Jun 20, 2019
Messages
7
I wrote some VBA to that adds a .csv file as a power query in Excel. The file location can change. I have some code that allows you to pick where the files are located, but I can't figure how to use that input to tell it where to look.

Below is what I have for getting the file location.

Dim fd As FileDialog
Dim sPath As String
Dim GetFileName As String

Set fd = Application.FileDialog(msoFileDialogFolderPicker)

If fd.Show = -1 Then
sPath = fd.SelectedItems(1)
End If

'sPath now holds the path to the folder or nothing if the user clicked the cancel button
'MsgBox sPath


This is what I have for importing the file.

ActiveWorkbook.Queries.Add Name:="FileName", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""C:\CAN\CHANGE\STAYS\SAME\FileName.csv""),[Delimiter="","", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Promoted Hea" & _
"ders"",{{""Part"", type text}, {""Color"", Int64.Type}, {""Quantity"", Int64.Type}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""

Workbooks(GetFileName).Connections.Add2 "Query - FileName", _
"Connection to the 'FileName' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""FileName"";Extended Properties=""""" _
, "SELECT * FROM [FileName]", 2

I'm not sure that is good way to approach this. I hope I explained this well enough to understand.
 

Excel Facts

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.

Forum statistics

Threads
1,215,025
Messages
6,122,731
Members
449,093
Latest member
Mnur

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