Event2020
07-04-2024, 02:56 PM
The sub below calls a delimited text file and it is then supposed to pass the file name and file path to the Query in the appropiate places in the code below.
The Query then processes the data according to my needs before writing the result to a new worksheet.
The Query VBA was created by me carefully recording each step in a macro which works perfectly except the query only wants to open the file that was opened when the macro was record which is expected behaviour.
I have been trying to add a file picker dialog to the code that passes the chosen (picked) file name and the file path to the correct parts of the query that need that information. This way the query could be used over and over again.
Fine in theory, but when I try and import a file I get...
"Run-time error '-2147024809 (80070057)': The query name 'C:\Users\Username\Desktop\Test Data\Fake Test Data.1.txt' contains characters that are not valid.'"
I do not understand why this is happening as it is the same file and path that was used to record the Query.
I have tried to counter the error by declairing the characters that occur in the file name and path ":", "", and "." but that has changed nothing and Querys are a black art to me.
I would be grateful for any help.
I have attached a small Example Workbook and a small Fake/Dummy data.txt file.
Sub ImportTest()
Dim fd As FileDialog
Dim selectedFilePath As String
Dim selectedFileName As String
Dim backSlash As String
Dim colonString As String
Dim dot As String
' This creates a FileDialog object as a File Picker
Set fd = Application.FileDialog(msoFileDialogFilePicker)
' Filter to only allow text files to be selected
fd.Filters.Add "Text Files", "*.txt"
' Shows the File Picker dialog box
If fd.Show = -1 Then
selectedFilePath = fd.SelectedItems(1) ' Gets the selected file path
Else
Exit Sub ' User cancelled, exit the sub
End If
ActiveWorkbook.Queries.Add Name:=selectedFilePath, Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""C:\Users\Username\Desktop\Test Data\Fake Test Data.1.txt""),[Delimiter="":"", Columns=2, Encoding=65001, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}})," & Chr(13) & "" & Chr(10) & " #""Added Index"" = Table.AddIndexColumn(#""Changed Type"", """ & _
"Index"", 1, 1, Int64.Type)," & Chr(13) & "" & Chr(10) & " #""Filtered Rows"" = Table.SelectRows(#""Added Index"", each ([Column1] = ""Company Name"" or [Column1] = ""Complete name"" or [Column1] = ""Credit Card #"" or [Column1] = ""Credit Card Type"" or [Column1] = ""Currency"" or [Column1] = ""email""))," & Chr(13) & "" & Chr(10) & " #""Pivoted Column"" = Table.Pivot(#""Filtered Rows"", List.Distinct(#""Filtered R" & _
"ows""[Column1]), ""Column1"", ""Column2"")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Pivoted Column"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Fake Test Data 1"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Fake Test Data 1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Fake_Test_Data_1"
.Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("Fake_Test_Data_1").Unlist
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
Application.CommandBars("Queries and Connections").Visible = False
End Sub
The Query then processes the data according to my needs before writing the result to a new worksheet.
The Query VBA was created by me carefully recording each step in a macro which works perfectly except the query only wants to open the file that was opened when the macro was record which is expected behaviour.
I have been trying to add a file picker dialog to the code that passes the chosen (picked) file name and the file path to the correct parts of the query that need that information. This way the query could be used over and over again.
Fine in theory, but when I try and import a file I get...
"Run-time error '-2147024809 (80070057)': The query name 'C:\Users\Username\Desktop\Test Data\Fake Test Data.1.txt' contains characters that are not valid.'"
I do not understand why this is happening as it is the same file and path that was used to record the Query.
I have tried to counter the error by declairing the characters that occur in the file name and path ":", "", and "." but that has changed nothing and Querys are a black art to me.
I would be grateful for any help.
I have attached a small Example Workbook and a small Fake/Dummy data.txt file.
Sub ImportTest()
Dim fd As FileDialog
Dim selectedFilePath As String
Dim selectedFileName As String
Dim backSlash As String
Dim colonString As String
Dim dot As String
' This creates a FileDialog object as a File Picker
Set fd = Application.FileDialog(msoFileDialogFilePicker)
' Filter to only allow text files to be selected
fd.Filters.Add "Text Files", "*.txt"
' Shows the File Picker dialog box
If fd.Show = -1 Then
selectedFilePath = fd.SelectedItems(1) ' Gets the selected file path
Else
Exit Sub ' User cancelled, exit the sub
End If
ActiveWorkbook.Queries.Add Name:=selectedFilePath, Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""C:\Users\Username\Desktop\Test Data\Fake Test Data.1.txt""),[Delimiter="":"", Columns=2, Encoding=65001, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}})," & Chr(13) & "" & Chr(10) & " #""Added Index"" = Table.AddIndexColumn(#""Changed Type"", """ & _
"Index"", 1, 1, Int64.Type)," & Chr(13) & "" & Chr(10) & " #""Filtered Rows"" = Table.SelectRows(#""Added Index"", each ([Column1] = ""Company Name"" or [Column1] = ""Complete name"" or [Column1] = ""Credit Card #"" or [Column1] = ""Credit Card Type"" or [Column1] = ""Currency"" or [Column1] = ""email""))," & Chr(13) & "" & Chr(10) & " #""Pivoted Column"" = Table.Pivot(#""Filtered Rows"", List.Distinct(#""Filtered R" & _
"ows""[Column1]), ""Column1"", ""Column2"")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Pivoted Column"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Fake Test Data 1"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Fake Test Data 1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Fake_Test_Data_1"
.Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("Fake_Test_Data_1").Unlist
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
Application.CommandBars("Queries and Connections").Visible = False
End Sub