How do I change a Parameter in Power Query without it converting the value to a formula? - excel

I was following the instructions on this thread:
How to Change Excel Power Query Paramaters with VBA
which lists the following code for changing a Power Query parameter:
ThisWorkbook.Queries([ParameterName]).Formula = 'New code here
However it converts the value into a formula and adds "= " to the front of it:
I need to update the source of my query because the GUID expires and needs to be refreshed.
Source = Xml.Tables(Web.Contents("http://api.aceproject.com/?fct=getprojects&guid=" & GUID & "&Filtercompletedproject=False&projecttemplate=0&assignedonly=True")),
The only solutions I can find require using a value stored in a cell, but I want to avoid storing the GUID in a cell for security reasons.
Using VBA how can I change either just the parameter value (without it converting into a formula) or the entire source URL?

The solution was using double quotes to force a text value to the formula:
ThisWorkbook.Queries("GUID").Formula = """dogs"""
Here's the final version, which passes the variable through as text:
Sub RefreshQuery_Click()
ThisWorkbook.Queries("GUID").Formula = """" & GUID & """"
End Sub
To ensure the query retains the parameter property, add in the following meta data:
ThisWorkbook.Queries("GUID").Formula = """" & GUID & """" & " meta [IsParameterQuery=true, Type=""Text"", IsParameterQueryRequired=true]"

Related

VBA Dynamically Building A Formula From An Array

I am trying to dynamically construct a formula based on an array that I have generated from a cell (separated by commas), as there is a varying amount of elements in the array I need to append a new "formula block" with the updated element to use in a if statement that is generated after the for each loop. VBA is throwing a type mismatch error in the InvestigateFormula = line, here is my code:
For Each Type In ToIgnore()
InvestigateFormula = "(ISNUMBER(SEARCH(*" & ToIgnore(Type) & "*," & _
AssetTypesCol & "2)),"
FullFormula = InvestigateFormula & FullFormula
Next Asset
FinalInvestigateFormula = "=IF(OR" & FullFormula & "),""Ignore"", """")"
ActiveCell.Formula = FinalInvestigateFormula
Please let me know if there is an easier way of doing this or how I might be able to correct the above code. Btw I am not declaring a variant I am simply declaring ToIgnore() as String and using the split function from the variable which contains the comma separated values to generate the array/items to loop over.
"Type" is a reserved name? Try strType instead?

Expression.Error when dynamically passing in Teradata SQL query (with column aliases) to ODBC query

I have a macro that prompts me for a SQL query (unless it was called by another Sub, in which case it uses the argument that was passed into its optional string parameter as the query) and then executes the query against my Teradata SQL database.
It works fine, unless there's a column alias containing a space in the query.
Example query:
SELECT 2 + 2 AS "Query Result";
Error:
Run-time error '1004':
[Expression.Error] The name 'Source' wasn't recognized. Make sure it's spelled correctly.
The line of code which I believe is the culprit is as follows (my apologies for the readability-- I recorded the macro, modified it just enough to get it to work somewhat dynamically and then haven't touched it since).
ActiveWorkbook.Queries.Add Name:=queryName, formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=my-server-name"", " & Chr(34) & code & Chr(34) & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
I assume it has to do with the fact that the example query above has double quotes for the alias, which are confusing the syntax when trying to be interpolated. Any help would be greatly appreciated!
Here's what the string for the formula is set to in this line:
ActiveWorkbook.Queries.Add Name:=queryName, formula:=<string here>
after all the chr() and concatenation are done:
let
Source = Odbc.Query("dsn=my-server-name", "<code>")
in
Source
That token <code> is replaced by whatever is in your variable code. So I suspect you are correct in that this formula would need to have it's double quotes escaped fully.
In other words this string you are building form Formula is going to be evaluated as code itself, and even in that evaluation it will be passing more code (your SQL) onto the Teradata server to be evaluated there.
You are in code inception. VBA code writing powerquery code writing Teradata code.
Understanding that and guessing a bit here, I'm thinking your current code variable looks something like:
code="SELECT 2 + 2 AS ""Query Result"";"
Your double quotes are already escaped for VBA. BUT because you have to survive another round of eval in powerquery you need to escape once again. Instead:
code="SELECT 2 + 2 AS """"Query Result"""";"
*I think...

how to write query with function inside it in access vba?

Lets suppose, vba code has
Dim SQL as String
SQL ="select * from table"
I found function that helps to combine values from related rows into a single concatenated string value.But when i implemented to my code it didn't work because double quotation inside query creating errors.What could be best format to make syntax valid in vba.The function is given below and link is (Combine values from related rows into a single concatenated string value).
SELECT
i.N_ID,
i.F_Name,
i.L_Name,
ConcatRelated(
"Course_ID",
"tbl_Courses",
"N_ID = '" & [N_ID] & "'"
) AS Course_IDs
FROM tbl_Instructors AS i;
Most likely, your ID is numeric, not text, thus no single-quotes:
SELECT
i.N_ID,
i.F_Name,
i.L_Name,
ConcatRelated(
"Course_ID",
"tbl_Courses",
"N_ID = " & [N_ID] & ""
) AS Course_IDs
FROM tbl_Instructors AS i;

Passing string result to query then export as csv

Good Afternoon,
I have an access query that contains a list of all my customers lets call that CUS
I have another query that has a list of ORDERS
I would like to write some VBS that cycles through the customer list and exports a csv file containing all orders that belong to that customer.
The vba would then move on to the next customer on the list and perform the same action.
Any help would be great.
Snippet of code below
almost there cant get the WHERE condition working it keeps displaying a popup for me to populate however the same string is feeding the msgbox fine here is a snippet below tht is within the loop
strcustcode = rs!OCUSTCODE
ordercount = rs!orders
TIMEFILE = Format$(Time, "HHMM")
MsgBox ([strcustcode] & " has " & [ordercount] & " orders")
StrSQL = "Select * From [24-ND_Cus] where [24-ND_Cus].[OCUSTCODE] = strcustcode "
Set qd = db.CreateQueryDef("tmpExport", StrSQL)
DoCmd.TransferText acExportDelim, , "tmpExport", "c:file.csv" db.QueryDefs.Delete "tmpExport" –
Don't use [ ] around VBA variables. Don't use parens for the MsgBox when you just want to give user a message. The parens make it a function that requires a response by user to set a variable.
MsgBox strcustcode & " has " & ordercount & " orders"
Concatenate the variable into the SQL statement. If OCUSTCODE is a text type field, use apostrophe delimiters for the parameter.
StrSQL = "Select * From [24-ND_Cus] Where [OCUSTCODE] = '" & strcustcode & "'"
I don't advise code that routinely modifies design and changing a query SQL statement is changing design. If the only change is filter criteria and a dynamic parameterized query won't work, I suggest a 'temp' table - table is permanent, data is temporary. Delete and write records to the table and export the table.

Excel VBA query table properties

I have an odbc query table which is currently working, but I need to define the field selected form the database by a value in cell D18.
The following code should replace the command text in the query table properties but it doesn't work.
debug says "Subscript out of range". if i debug and run ?text in the immediate window then run this resulting text line in SQL it returns the correct value, so the sql statement is right. what have i got wrong in the vba syntax
Sub Accrual()
Text = "SELECT "
Text = Text & "BALANCE.CDTLED_" & Range("D11").Value - 1 & " "
Text = Text & "FROM x3sov.SOVEX.BALANCE BALANCE "
Text = Text & "WHERE (BALANCE.ACC_0='2109') AND (BALANCE.FCY_0='S01')"
Sheets("Control").QueryTables(1).CommandText = Text
End Sub
any help much appreciated
Since Excel introduced ListObjects (called Tables in the UI), you can no longer rely on QueryTables.Count to get to all the external data connections. If you don't have any QueryTables, then the external data connection goes through a ListObject.
Sheet1.ListObjects(1).QueryTable.CommandText = Text
Note that ListObject doesn't have a QueryTables property, but a QueryTable property because there's always only one.

Resources