Having a Token Error when creating PowerQuery - excel

This sub creates a powerquery with the source from a folderpath, it gets all the excel files from the folder and consolidate and filter it.
I am having an error whenever I make Source = Folder.Files("Dir") dynamic
Is there a way to make the paths dynamic so that I will just refresh the query page and update the value of the SourcePath for Folder.Files in my Settings sheet.
I have this error
Runtime-error '1004':
[Expression.Error] The name 'Source' wasn't recognized, Make sure it's spelled correctly.
in this line .Refresh BackgroundQuery:=False
If I create a value for SourcePath referencing a cell in a sheet with this format "C:\Path" ,It has this error
Error:
Runtime Error '1004':
Application Defined or Object-defined error
in this line
.ListObject.DisplayName = "Data"
Sub AddSaveQuery()
'Set Objects
Dim SourcePath As String
Dim SavePath As String
SourcePath = Worksheets("Home").Range("G21").Value
SavePath = Worksheets("Home").Range("G8").Value
Sub AddSaveQuery()
'Set Objects
Dim SourcePath As String
Dim SavePath As String
SourcePath = Worksheets("Home").Range("G21").Value
SavePath = Worksheets("Home").Range("G8").Value
'Will set first condition for sheet2
'Filter Column2 Begins with FilterValue1
ActiveWorkbook.Queries.Add Name:="Data", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Folder.Files(""" & SourcePath & """)," & Chr(13) & "" & Chr(10) & " #""Filtered Hidden Files1"" = Table.SelectRows(Source, Each [Attributes]?[Hidden]? <> true)," & Chr(13) & "" & Chr(10) & " #""Invoke Custom Function1"" = Table.AddColumn(#""Filtered Hidden Files1"", ""Transform File"", Each #""Transform File""([Content]))," & Chr(13) & "" & Chr(10) & " #""Renamed Columns1""" & _
" = Table.RenameColumns(#""Invoke Custom Function1"", {""Name"", ""Source.Name""})," & Chr(13) & "" & Chr(10) & " #""Removed Other Columns1"" = Table.SelectColumns(#""Renamed Columns1"", {""Source.Name"", ""Transform File""})," & Chr(13) & "" & Chr(10) & " #""Expanded Table Column1"" = Table.ExpandTableColumn(#""Removed Other Columns1"", ""Transform File"", Table.ColumnNames(#""Transform File""(#""Sample File"")))," & Chr(13) & "" & _
"" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Expanded Table Column1"",{{""Source.Name"", Type text}, {""Column1"", Type any}, {""Column2"", Type any})," & Chr(13) & "" & Chr(10) & " #""Removed Other Columns"" = Table.SelectColumns(#""Column1" & _
"ed Type"",{""Column2""})," & Chr(13) & "" & Chr(10) & " #""Filtered Rows"" = Table.Sel" & _
"ectRows(#""Removed Other Columns"", Each Text.StartsWith([Column2], ""FilterValue1""))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filtered Rows"""
ActiveWorkbook.Queries.Add Name:="Parameter1", Formula:= _
"#""Sample File"" meta [IsParameterQuery=true, BinaryIdentifier=#""Sample File"", Type=""Binary"", IsParameterQueryRequired=true]"
ActiveWorkbook.Queries.Add Name:="Transform Sample File", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(Parameter1, null, true)," & Chr(13) & "" & Chr(10) & " Page1_Sheet = Source{[Item=""Page1"",Kind=""Sheet""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Page1_Sheet, [PromoteAllScalars=true])" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Promoted Headers"""
ActiveWorkbook.Queries.Add Name:="Sample File", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Folder.Files(""" & SourcePath & """)," & Chr(13) & "" & Chr(10) & " Navigation1 = Source{0}[Content]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Navigation1"
ActiveWorkbook.Queries.Add Name:="Transform File", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = (Parameter1) => let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(Parameter1, null, true)," & Chr(13) & "" & Chr(10) & " Page1_Sheet = Source{[Item=""Page1"",Kind=""Sheet""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Page1_Sheet, [PromoteAllScalars=true])" & Chr(13) & "" & Chr(10) & " in" & Chr(13) & "" & Chr(10) & " #""Promoted Headers""" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Data;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Data]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Data"
.Refresh BackgroundQuery:=False
End With
Workbooks("CognosDataCleaner2.xlsm").Connections.Add2 "Query - Parameter1", _
"Connection To the 'Parameter1' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Parameter1;Extended Properties=""""" _
, "SELECT * FROM [Parameter1]", 2
Workbooks("CognosDataCleaner2.xlsm").Connections.Add2 _
"Query - Transform Sample File", _
"Connection To the 'Transform Sample File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Transform Sample File"";Extended Properties=""""" _
, "SELECT * FROM [Transform Sample File]", 2
Workbooks("CognosDataCleaner2.xlsm").Connections.Add2 "Query - Sample File", _
"Connection To the 'Sample File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Sample File"";Extended Properties=""""" _
, "SELECT * FROM [Sample File]", 2
Workbooks("CognosDataCleaner2.xlsm").Connections.Add2 "Query - Transform File" _
, "Connection To the 'Transform File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Transform File"";Extended Properties=""""" _
, "SELECT * FROM [Transform File]", 2
'Rename New Query Sheet to TEST1
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "TEST1"
Sheets("TEST1").Select
Workbooks("Book1").Connections.Add2 "Query - Transform File", _
"Connection To the 'Transform File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Transform File"";Extended Properties=""""" _
, "SELECT * FROM [Transform File]", 2
Workbooks("Book1").Connections.Add2 "Query - Sample File", _
"Connection To the 'Sample File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Sample File"";Extended Properties=""""" _
, "SELECT * FROM [Sample File]", 2
Sheets("TEST1").Copy
'SAVE PATH
ChDir SavePath
ActiveWorkbook.SaveAs Filename:= _
SavePath _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
End Sub
I have created an Object SourcePath and in that path I concat it so it does have the value like this:
"Directory"
A1 = "
A2 = "
A3 = Directory or path
=CONCAT(A1 & A3 & A2)
I also have set Source as String to make it an object aswell.

You need quotes round the path, so:
"let" & Chr(13) & "" & Chr(10) & " Source = Folder.Files(""" & SourcePath & """),"

Related

How to update Source ID in ActiveWorkbook.Queries.Add

I'm trying to add parameters into a ActiveWorkbook.Queries.Add
I have managed to change all except the on in 'Source{[Id=""Table001""]}', inside the ActiveWorkbook.Queries.Add
I have tried Source{[Id=" & TableOnly & "]} but I get an error in line 'ActiveWorkbook.Queries.Add': The import table Table001 matches no exports
See below the full code and where 'Source{[Id=""Table001""]}' is located
For i = 1 to 3
TableName = "Table00" & i & " (Page " & i + 2 & ")" 'Example: "Table001 (Page 3)"
DispName = "Table00" & i & "__Page_" & i + 2 & "" 'Example: "Table001__Page_3"
TableOnly = "Table00" & i 'Example: Table001
ActiveWorkbook.Queries.Add Name:=TableName, Formula:= _
"let" & Chr(13) & "" & Chr(10) & _
" Source = Pdf.Tables(File.Contents(""C:\Sample.pdf""), [Implementation=""1.3""])," & Chr(13) & "" & Chr(10) & _
" " & TableOnly & " = Source{[Id=""Table001""]}[Data]," & Chr(13) & "" & Chr(10) & _
" #""Changed Type"" = Table.TransformColumnTypes(" & TableOnly & ",{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", " & _
"type text}, {""Column6"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & TableName & ";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [" & TableName & "]")
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = DispName
.Refresh BackgroundQuery:=False
End With
Next
I found the problem. I had to add an addition inverted comas at each end as:
Source{[Id=""" & TableOnly & """]}
Hope is helps someone.

VBA throws an error when a string is changed to a variable with exact string

This is my vba code for powerquery function
ActiveWorkbook.Queries.Add Name:="Or ORder", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(File.Contents(""C:\Users\DDK\Downloads\excel.xlsx""), null, true)," & Chr(13) & "" & Chr(10) & " Sheet1_Sheet = Source{[Item=""Sheet1"",Kind=""Sheet""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Sheet1_Sheet, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Promoted Headers"",{{""Column1"", type any}" & _
", {""CROWN"", type any}, {""March 15th, 2021"", type text}, {""Column4"", type any}, {""Column5"", type any}})," & Chr(13) & "" & Chr(10) & " #""Removed Top Rows"" = Table.Skip(#""Changed Type"",2)," & Chr(13) & "" & Chr(10) & " #""Renamed Columns"" = Table.RenameColumns(#""Removed Top Rows"",{{""Column1"", ""QTY""}, {""CROWN"", ""ITEM""}, {""March 15th, 2021"", ""Part""}, {""Column5"", ""Price""}})," & Chr(13) & "" & Chr(10) & " #""Filter" & _
"ed Rows"" = Table.SelectRows(#""Renamed Columns"", each [QTY] <> null and [QTY] <> """")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Filtered Rows"""
ActiveWorkbook.Worksheets.Add.Name = "Our Order"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Or ORder"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Or ORder]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Or_ORder"
.Refresh BackgroundQuery:=False
End With
When the file directory for the source is changed to a variable like this
Dim fileOrder as String
fileOrder = "C:\Users\Ddk\Downloads\excel.xlsx"
....
Source = Excel.Workbook(File.Contents(fileOrder), null, true)," & Chr(13) & "" & Chr(10) ""....
It throws an error when it reaches .Refresh BackgroundQuery:=False. Why is it? Even when it is the exact same string it gives an error [Expression.Error] The import Order matches no exports. Did you miss a module reference?
The thing is I want user to select the excel file for power query through VBA that's why I need to have a variable on file directory.
Why not use VBA to write the path to a named cell range, and have powequery read it in?
let Source = Csv.Document(File.Contents(Excel.CurrentWorkbook(){[Name="RangeName"]}[Content]{0}[Column1]),
or
let Source = Excel.Workbook(File.Contents(Excel.CurrentWorkbook(){[Name="RangeName"]}[Content]{0}[Column1]), null, true),

VBA QueryTables not working with Yahoo Finance

I'm trying this simple Sub (in Excel 2019) to import tables from a specific Yahoo Finance page.
It works with other websites, but with Yahoo Finance, I keep getting the same message "This Web query returned no data. To change..........." and no data is extracted.
I couldn't figure out the reason.
Sub ImportTable()
Dim ws As Worksheet
Dim qt As QueryTable
Dim qurl As String
qurl = "https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT"
Set ws = worksheets.Add
Set qt = ws.QueryTables.Add( _
Connection:="URL;" & qurl, _
Destination:=Range("A1"))
With qt
.RefreshOnFileOpen = False
.Name = "test"
.WebFormatting = xlWebFormattingNone
.WebSelectionType = xlAllTables
.Refresh
End With
End Sub
You can instead set-up connections to the various tables which will add them to the data model (Alt + B + M). In the queries pane of data you can then chose where to load them to your workbook if you wish to see them. You can also just work with them in the data model and generate your final desired output.
Note:
The quicker way is, from ribbon, to do, data > from web > enter url > select tables of interest. This will set-up table connections without vba.
VBA:
Option Explicit
Public Sub AddYahooFinanceTableConnections()
Dim wb As ThisWorkbook
Set wb = ThisWorkbook
wb.Queries.Add Name:="Balance Sheet", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data10 = Source{10}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data10,{{""Total Cash (mrq)"", type text}, {""131.99B"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Cash Flow Statement", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data11 = Source{11}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data11,{{""Column1"", type text}, {""Column2"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Dividends & Splits", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data5 = Source{5}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data5,{{""Forward Annual Dividend Rate"", type text}, {""2.24"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Fiscal Year", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data6 = Source{6}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data6,{{""Column1"", type text}, {""Column2"", type date}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Income Statement", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data9 = Source{9}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data9,{{""Revenue (ttm)"", type text}, {""153.28B"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="People Also Watch", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data12 = Source{12}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data12,{{""Symbol"", type text}, {""Last Price"", type number}, {""Change"", type number}, {""% Change"", Percentage.Type}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Profitability", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data7 = Source{7}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data7,{{""Column1"", type text}, {""Column2"", Percentage.Type}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Share Statistics", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data4 = Source{4}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data4,{{""Avg Vol (3 month)"", type text}, {""30.36M"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Stock Price History", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data3 = Source{3}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data3,{{""Beta (5Y Monthly)"", type text}, {""0.79"", type number}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Table 0", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Column1"", type text}, {""Column2"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Queries.Add Name:="Table 1", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT""))," & Chr(13) & "" & Chr(10) & " Data1 = Source{1}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data1,{{""Column1"", type text}, {""Column2"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
wb.Connections.Add2 "Query - Balance Sheet", _
"Connection to the 'Balance Sheet' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Balance Sheet;Extended Properties=" _
, """Balance Sheet""", 6, True, False
wb.Connections.Add2 "Query - Cash Flow Statement", _
"Connection to the 'Cash Flow Statement' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Cash Flow Statement;Extended Properties=" _
, """Cash Flow Statement""", 6, True, False
wb.Connections.Add2 "Query - Dividends & Splits", _
"Connection to the 'Dividends & Splits' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Dividends & Splits;Extended Properties=" _
, """Dividends & Splits""", 6, True, False
wb.Connections.Add2 "Query - Fiscal Year", _
"Connection to the 'Fiscal Year' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Fiscal Year;Extended Properties=" _
, """Fiscal Year""", 6, True, False
wb.Connections.Add2 "Query - Income Statement", _
"Connection to the 'Income Statement' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Income Statement;Extended Properties=" _
, """Income Statement""", 6, True, False
wb.Connections.Add2 "Query - People Also Watch", _
"Connection to the 'People Also Watch' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=People Also Watch;Extended Properties=" _
, """People Also Watch""", 6, True, False
wb.Connections.Add2 "Query - Profitability", _
"Connection to the 'Profitability' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Profitability;Extended Properties=" _
, """Profitability""", 6, True, False
wb.Connections.Add2 "Query - Share Statistics", _
"Connection to the 'Share Statistics' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Share Statistics;Extended Properties=" _
, """Share Statistics""", 6, True, False
wb.Connections.Add2 "Query - Stock Price History", _
"Connection to the 'Stock Price History' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Stock Price History;Extended Properties=" _
, """Stock Price History""", 6, True, False
wb.Connections.Add2 "Query - Table 0", _
"Connection to the 'Table 0' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Table 0;Extended Properties=" _
, """Table 0""", 6, True, False
wb.Connections.Add2 "Query - Table 1", _
"Connection to the 'Table 1' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Table 1;Extended Properties=" _
, """Table 1""", 6, True, False
End Sub

using vba to loop a column of dates into the url line for web query and retrieve an exchange rate table from xe.com/currencytables

I have a column of dates (in Excel spreadsheet) and would like to insert these dates into the url line in the web query to generate an exchange rate tables which I would like to put them in the spreadsheets. For example:
Column A
2019-12-09
2019-12-08
2019-12-07
For each of these dates in column A, I would like insert them into the url line:
Below is a recorded VBA macro using --Get Data, from Web. Then I copy and paste the https://www.xe.com/currencytables/?from=USD&date=2019-12-10 into the url(pop up window), hit ok and choose table 0 to generate an exchange rate table for the date 2019-12-10. I would like to automate this process and use the dates in Column A. I don't have any experience in power query. Thank you for your help in advance.
Sub Macro2()
'
' Macro2 Macro
'
'
ActiveWorkbook.Queries.Add Name:="Table 0 (6)", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://www.xe.com/currencytables/?from=USD&date=2019-12-08""))," & Chr(13) & "" & Chr(10) & " Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Currency code ??"", type text}, {""Currency name ??"", type text}, {""Units per USD"", type number}, {""USD per Unit"", type number}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Table 0 (6)"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Table 0 (6)]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_0__6"
.Refresh BackgroundQuery:=False
End With
End Sub
For a test I've changed the url:
ActiveWorkbook.Queries.Add Name:="Table 0 (6)", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://www.xe.com/currencytables/?from=USD&date=" & Format(DateSerial(2019, 12, 8), "yyyy-mm-dd") & """))," & Chr(13) & "" & Chr(10) & " Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Currency code"", type text}, {""Currency name"", type text}, {""Units per USD"", type number}, {""USD per Unit"", type number}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
ActiveWorkbook.Worksheets.Add
So under format(dateserial()) you can put your variable with date from the cell.
I've also changed Currency code ?? and Currency name ?? to Currency code and Currency name and edited them manually in power query editor in Excel the same way, as there is a problem with those arrows in column names.
If you would like to generate tables for all dates at once, then you have to solve that issue with arrows in the column name (or it is solved already?).
Next step is to make sure that table names are unique and generated automatically.
Last step would be the for loop to go through cells with dates.
UPDATE:
Ok, below you can find updated code. I've deleted column formatting for problematic columns with special characters. Variables for table name and date are created so now it will be extremely easy to extend that code to create tables for how much historic data you want :)
Option Explicit
Sub DownloadExchangeRates()
'Set variables
Dim wb As Workbook
Dim wbs As Worksheet
Dim mydate As Date
Dim table_name As String
Dim table_display_name As String
Set wb = ThisWorkbook
mydate = DateSerial(2019, 12, 7)
table_name = "Table " & Format(mydate, "yyyy-mm-dd")
table_display_name = "Table_" & Format(mydate, "yyyy_mm_dd")
' Create connection
wb.Queries.Add _
Name:=table_name, _
Formula:= _
"let" & Chr(13) & "" & Chr(10) & _
" Source = Web.Page(Web.Contents(""https://www.xe.com/currencytables/?from=USD&date=" & Format(mydate, "yyyy-mm-dd") & """))," & Chr(13) & "" & Chr(10) & _
" Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & _
" #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""Units per USD"", type number}, {""USD per Unit"", type number}})" & Chr(13) & "" & Chr(10) & _
"in" & Chr(13) & "" & Chr(10) & _
" #""Changed Type"""
'Create new worksheet
wb.Worksheets.Add
Set wbs = wb.ActiveSheet
wbs.Name = "Currency for " & Format(mydate, "yyyy-mm-dd")
With wbs.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & """" & table_name & """" & ";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [" & table_name & "]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = table_display_name
.Refresh BackgroundQuery:=False
End With
End Sub

Record Macro: Get Data from File

I'll start by admitting Macro's are generally not my thing and writing the code certainly isn't - but in the situation and having read about recording macros i thought it could work for me. If this isn't the way to do it feel free to say so and i will dismiss the idea for the time being until i can do more research and write the code.
Essentially the steps I'm trying to achieve
- Starting from a blank workbook
- Use macro to get data from a folder in our company network containing about 15 workbooks which all have the same internal format and information but relate to different geographic locations
- I recorded the macro using exactly the steps i use if i were doing the task manually which i know works fine
the full code text is below. Upon running i immediately get a run-time error which when debugged highlights the first section and states "A query with the name 'Pipeline Working' already exists. "Pipeline Working" is the name of the folder in which contains the workbooks to import, from there I'm already lost.
Any help appreciated.
Sub PipelinePredictions()
'
' PipelinePredictions Macro
' Import Data from File for Pipeline Predictions
'
'
ActiveWorkbook.Queries.Add Name:="Pipeline Working", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Folder.Files(""\\hofileserver\Accounts\ACCOUNTS\Lettings Stats 2018 Qtr 4\Pipelines\Pipeline Working"")," & Chr(13) & "" & Chr(10) & " #""Filtered Hidden Files1"" = Table.SelectRows(Source, each [Attributes]?[Hidden]? <> true)," & Chr(13) & "" & Chr(10) & " #""Invoke Custom Function1"" = Table.AddColumn(#""Filtered Hidden Files1"", ""Transform File from Pipeline Working"", each #""Transform File f" & _
"rom Pipeline Working""([Content]))," & Chr(13) & "" & Chr(10) & " #""Renamed Columns1"" = Table.RenameColumns(#""Invoke Custom Function1"", {""Name"", ""Source.Name""})," & Chr(13) & "" & Chr(10) & " #""Removed Other Columns1"" = Table.SelectColumns(#""Renamed Columns1"", {""Source.Name"", ""Transform File from Pipeline Working""})," & Chr(13) & "" & Chr(10) & " #""Expanded Table Column1"" = Table.ExpandTableColumn(#""Removed Other Columns" & _
"1"", ""Transform File from Pipeline Working"", Table.ColumnNames(#""Transform File from Pipeline Working""(#""Sample File"")))," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Expanded Table Column1"",{{""Source.Name"", type text}, {""Column1"", type any}, {""Column2"", type text}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", type number}" & _
", {""Column6"", Percentage.Type}, {""Column7"", Int64.Type}, {""Column8"", type number}, {""Column9"", type number}, {""Column10"", type number}, {""Column11"", type any}, {""Column12"", type datetime}, {""Column13"", type text}})," & Chr(13) & "" & Chr(10) & " #""Renamed Columns"" = Table.RenameColumns(#""Changed Type"",{{""Source.Name"", ""Branch""}, {""Column1"", ""Week Booked""}, {""Col" & _
"umn2"", ""Neg""}, {""Column3"", ""Property""}, {""Column4"", ""Service Type""}, {""Column5"", ""Rent""}, {""Column6"", ""Percentage Fee""}, {""Column7"", ""Term""}, {""Column8"", ""Fee""}, {""Column9"", ""Admin""}, {""Column10"", ""Total Fees""}, {""Column11"", ""Rent G'tee""}})," & Chr(13) & "" & Chr(10) & " #""Changed Type1"" = Table.TransformColumnTypes(#""Renamed Columns"",{{""Column12" & _
""", type date}})," & Chr(13) & "" & Chr(10) & " #""Renamed Columns2"" = Table.RenameColumns(#""Changed Type1"",{{""Column12"", ""Move in Date""}, {""Column13"", ""Notes""}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Renamed Columns2"""
ActiveWorkbook.Queries.Add Name:="Sample File Parameter1", Formula:= _
"#""Sample File"" meta [IsParameterQuery=true, BinaryIdentifier=#""Sample File"", Type=""Binary"", IsParameterQueryRequired=true]"
ActiveWorkbook.Queries.Add Name:= _
"Transform Sample File from Pipeline Working", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(#""Sample File Parameter1"", null, true)," & Chr(13) & "" & Chr(10) & " #""'A Pipeline$'Print_Area1"" = Source{[Name=""'A Pipeline$'Print_Area""]}[Data]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""'A Pipeline$'Print_Area1"""
ActiveWorkbook.Queries.Add Name:="Sample File", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Folder.Files(""\\hofileserver\Accounts\ACCOUNTS\Lettings Stats 2018 Qtr 4\Pipelines\Pipeline Working"")," & Chr(13) & "" & Chr(10) & " Navigation1 = Source{0}[Content]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Navigation1"
ActiveWorkbook.Queries.Add Name:="Transform File from Pipeline Working", _
Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = (#""Sample File Parameter1"") => let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(#""Sample File Parameter1"", null, true)," & Chr(13) & "" & Chr(10) & " #""'A Pipeline$'Print_Area1"" = Source{[Name=""'A Pipeline$'Print_Area""]}[Data]" & Chr(13) & "" & Chr(10) & " in" & Chr(13) & "" & Chr(10) & " #""'A Pipeline$'Print_Area1""" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Pipeline Working"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Pipeline Working]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_ExternalData_1"
.Refresh BackgroundQuery:=False
End With
Workbooks("Book1").Connections.Add2 "Query - Sample File Parameter11", _
"Connection to the 'Sample File Parameter1' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Sample File Parameter1"";Extended Properties=""""" _
, "SELECT * FROM [Sample File Parameter1]", 2
Workbooks("Book1").Connections.Add2 _
"Query - Transform Sample File from Pipeline Working1", _
"Connection to the 'Transform Sample File from Pipeline Working' query in the workbook." _
, Array( _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Transform Sample File from Pipeline Working"";Extended Propert" _
, "ies="""""), "SELECT * FROM [Transform Sample File from Pipeline Working]", 2
Workbooks("Book1").Connections.Add2 "Query - Sample File1", _
"Connection to the 'Sample File' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Sample File"";Extended Properties=""""" _
, "SELECT * FROM [Sample File]", 2
Workbooks("Book1").Connections.Add2 _
"Query - Transform File from Pipeline Working1", _
"Connection to the 'Transform File from Pipeline Working' query in the workbook." _
, _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Transform File from Pipeline Working"";Extended Properties=""""" _
, "SELECT * FROM [Transform File from Pipeline Working]", 2
Windows("Book3").Activate
Range("A1").Select
End Sub
This opens all workbooks in folder and copies the range called print area into the current spreadsheet - it assumes this code is in a blank workbook
Sub ImportData()
Const FolderToImport = "C:\Pipeline Working\" 'adjust as suits - keep last \ at end
Dim s As String
s = Dir(FolderToImport & "*.xl??")
Do While s <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(FolderToImport & s, False, True)
wb.Sheets(1).Range("print area").Copy Destination:= _
ThisWorkbook.Worksheets(1).Range("a" & Rows.Count).End(xlUp).Offset(1, 0)
wb.Close False
s = Dir()
Loop
End Sub

Resources