Excel vba open csv import dialog

I have this vba code below that was generated by a macro recorder. It imports the csv file into the current excel sheet with certain column settings. Right now, the path to the csv file is hardcoded to "C: \ Users \ myuser \ Desktop \ logexportdata.csv". How can I change this so that a dialog prompt appears that asks the user to search for the CSV file to import?

Sub Import_log() With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;C:\Users\myuser\Desktop\logexportdata.csv", Destination:=Range( _ "$A$2")) .Name = "logexportdata" .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 = 2 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = False .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(5, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub 
+6
source share
1 answer

try the following:

 Sub Import_log() With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;" & getFile, Destination:=Range( _ "$A$2")) .Name = "logexportdata" .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 = 2 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = False .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(5, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub Function GetFile() As String Dim filename__path As Variant filename__path = Application.GetOpenFilename(FileFilter:="Csv (*.CSV), *.CSV", Title:="Select File To Be Opened") If filename__path = False Then Exit Function GetFile = filename__path End Function 
+7
source

Source: https://habr.com/ru/post/947732/


All Articles