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
Related
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.
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 & """),"
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
The original macro looks like this:
ActiveWorkbook.Queries.Add Name:="Table 0 (2)", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://www.reuters.com/companies/luv/financials/income-statement-annual""))," & Chr(13) & "" & Chr(10) & " Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data0,{{"""", type text}, {""31-Dec-19"", type number}, {""31-Dec-18"", type number}, {""31-Dec-17"", type text}, {""31-Dec-16"", type text}, {""31-Dec-15"", type tex" & _
"t}, {""Trend"", 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=""Table 0 (2)"";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Table 0 (2)]")
.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__2"
.Refresh BackgroundQuery:=False
Essentially this macro pulls a table from a excel web query from a specific URL (https://www.reuters.com/companies/luv/financials/income-statement-annual). The idea was I wanted to replace luv within the URL with a string variable so I could pull a table from many different sources depending on which URL I wanted to pull data from. I edited my macro to look like this (ticker is the string variable):
ActiveWorkbook.Queries.Add Name:="Table 0 (2)", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Web.Page(Web.Contents(""https://www.reuters.com/companies/""&ticker&""/financials/income-statement-annual""))," & Chr(13) & "" & Chr(10) & " Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Data0,{{"""", type text}, {""31-Dec-19"", type number}, {""31-Dec-18"", type number}, {""31-Dec-17"", type text}, {""31-Dec-16"", type text}, {""31-Dec-15"", type tex" & _
"t}, {""Trend"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
But when I do that I get a Run-time error '424': Object required on this line:
.ListObject.DisplayName = "Table_0__2"
The macro obviously works flawlessly before I attempt to modify the URL with a string variable. And I have checked, the URL's are identical except for (in this case) the name of the company which is what my string variable is supposed to represent. Any advice would be much appreciated.
when I compare a table and a dump text file. I would load a powerbi to get a text file and then compareit with my already created table, so as to displaye the matching onesThis is the code that I ve been using to load the dump and compare it with the already created table
ActiveWorkbook.Queries.Add Name:="dump", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""xx:\location.txt""),[Delimiter=""#(tab)"", Columns=17, Encoding=65001, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Promoted Headers"",{{""market"", Int64.Type}, {""category"", Int64.Type}, {""brand"", type text},{""brand status"", type text}, {""vendor_code"", type text}, {""status_last_update_date"", Int64.Type}})," & Chr(13) & "" & Chr(10) & " #""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each ([brand status] <> """" and [brand_status] <> ""Audit"" and [brand status] <> ""SUPPRESSED""))," & Chr(13) & "" & Chr(10) & " " & _
Workbooks("Sheet2").Connections.Add2 "Query - dump", _
"Connection to the 'dump' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""us dump"";Extended Properties=""""" _
, "SELECT * FROM [us dump]", 2
ActiveWorkbook.Queries.Add Name:="Table1", Formula:= _