Running a web query with parameter from a cell within Excel - excel

I am trying to do a GET request when I change a value in a cell.
The link here:
https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=(PARAMETER SHOULD BE HERE)&hoursBeforeNow=1
So what's in this cell, should change this query.
Is this possible, and if so, does anyone have a good solution for this?
Been trying to google all night but can't seem to find anyone that has done the same thing.

Adapting from this answer, this is a two-step process.
Firstly, create a named range for the cell that stores the value you will pass to the query. Details on how to do so are here. I used "StationName" as the name of the range but you can use any name you like.
Secondly, we need to incorporate the named range into the source for the query. To do so:
select any cell in the data table from the current query
click on the Query tab in the ribbon
click on Edit
look for the Query Settings panel at the right of the screen - if it's not there, go to View then click on Query Settings
the first entry in the Query Settings panel should be Source - click on that entry to select it
make sure that the formula bar is displayed by going to View then checking Formula Bar
the entry in the formula bar is too long to display so click on the V symbol at the end of the formula bar to expand it
edit the formula bar text to the text shown below - make sure to change the name of the Excel range shown at Name="StationName" to whichever name you have used
= Xml.Tables(Web.Contents("https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=" & Excel.CurrentWorkbook(){[Name="StationName"]}[Content]{0}[Column1] & "&hoursBeforeNow=1"))
This picture shows how things should now look:
Now go to Home and click on Close & Load.
You may get a warning about privacy settings - to fix this, I chose to give both the Excel file and the aviationweather.gov site the "public" level of privacy.
You can access the privacy settings by selecting a cell in the data table, going to Query and choosing Edit, going to Home and choosing Data Source Settings, selecting Global Permissions and then using Edit Permissions on the relevant entries.
To make the query automatically refresh when the cell value changes, we need to use some VBA. We will need to know which sheet the cell is on, the name of the named range which refers to that cell and the name of the query we want to refresh. The first two should be straightforward and the name of the query is just "Query - " followed by the name shown in the Queries & Connections panel.
Open up the VBA Editor with ALT-F11, double-click on the relevant sheet object in the Project Explorer to open up the related code module and paste in the following code (but change the name of the named range and the name of the query to match your names):
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Target, ThisWorkbook.Names("StationName").RefersToRange) _
Is Nothing And Target.Cells.Count = 1 Then
Application.EnableEvents = False
ThisWorkbook.Connections("Query - Get station from aviationweather dot gov").Refresh
Application.EnableEvents = True
End If
End Sub
Now changing the cell value should cause the query to refresh automatically
Here's some simple code to list the name of every connection in the workbook. In the VBA editor, use Insert > Module to create a new module and then paste in the following code:
Option Explicit
Sub listConnections()
Dim c As WorkbookConnection
For Each c In ThisWorkbook.Connections
MsgBox c.Name
Next c
End Sub
Each connection name will pop up in a message box like this:
and you can just copy the name you need when it pops up. You can copy the message box contents just by hitting CTRL-C but you'll need to edit out some extra stuff when you paste. Copying the message box shown above results in the following text being placed on the clipboard:
---------------------------
Microsoft Excel
---------------------------
Query - Get station from aviationweather dot gov
---------------------------
OK
---------------------------

I get daily Exchange Rate data from cbr.ru in this fashion.
screenshot of the Connection
http://www.cbr.ru/eng/currency_base/daily/?UniDbQuery.Posted=True&UniDbQuery.To=["Ticker"]
Where i use the date as a variable from an excel cell, in such a way that it refreshes automatically once the cell value changes.
(named the parameter as Ticker)
screenshot of the Parameters
Hope this uber simple method helps.

Related

Macro button to copy link in pivot table based on Slicer

I'm starting with a Pivot Table that has all my data. One of the data fields is a URL string that I ultimately want to send my users to.
To make searching through the pivot table as easy as possible, I've got a couple slicer windows to let the users click their search criteria. What I'd like to do, is based upon their search criteria (once narrowed down to one result), is have a Macro Button that automatically launches their browser (lets say internet explorer) with the link found in the pivot table.
I can figure out the launching of the browser (or just a copy text), but is there a way that I can program the Macro Button's action based upon the selections of the Slicers that are associated with my pivot table?
Any help would be much appreciated!
If I understood you correctly, you want to launch your code when only one link appears in PivotTable (after you apply slicers to it).
You can achieve this with Worksheet_PivotTableChangeSync event and helper cell.
lets assume you have your pivot table in column G, starting from cell G2. Enter this this formula =COUNTA(G3:G20) in cell G1(adjust range to your needs).
then in your worksheet module (not regular module) enter this code.
Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable)
Dim a As Long
a = Range("G1").Value
If a = 1 Then
'your code for link in cell G3
Else
End If
End Sub
Now when you slice your PivotTable to only one selection, COUNTA formula will evaluate to 1 and trigger Worksheet_PivotTableChangeSync event.

show data refreshed time in excel

I have an excel which has sql queries associated with it. I open the excel , click on Data->Refresh All and send across to the users.
When I click on refresh All , I want the refreshed date to appear in a cell on that sheet. Can you give some hint on this.
Add another SQL Query somewhere else in your workbook
SELECT GETDATE()
Make sure you refer to the same database your original query is referring to.
when you refresh the spread sheet the date will be updated as well.
Select Data ribbon
From Other Sources
From Microsoft Query
Choose DataBase (same as one used for the original Query)
"Query Wizard - Choose Columns" Click Cancel
"Do you want to continue editing the data in Query" Click Yes
"Add Tables" Click Close
Click on "SQL Button" and add the query there "SELECT GETDATE()"
Click OK
Click on Return data to Microsoft Excel
Rather than using the Ribbon to perform the Refresh, try a little macro like:
Sub Macro1()
ActiveWorkbook.RefreshAll
With Range("A1")
.Value = Now()
.NumberFormat = "mm/dd/yyyy hh:mm:ss"
End With
End Sub
Pick whatever cell you like.
after searching various Excel related sites (mrexcel.com, exceltown.com and answers.microsoft.com) i've decided that the best solution (for me) does NOT need Macro or another query:
add as a last column in your existing query whatever function provides the current date and time [for Ingres it's date('now')]
hide the column from the resulting table
in the cell that you desire to show the last date & time that your table was refreshed enter the formula max(j:j). substitute j with the column that you've hidden.
simple :)
This was the easiest way for me to get a refresh date. Add a =Date.Time.LocalNow() column. Hide Column. https://exceloffthegrid.com/power-query-get-refresh-date-time/

Can't use more than one combo box on excel

I have made two active X combo boxes for a list of 220 sites. Before making the active x combo box i have made a sheet that searches through my data and finds the sites that match with what i am typing as i go.
I then used the name manage, refering to the formula in the first cell of the list
=Sheet1!$G$2:INDEX(Sheet1!$G$2:$G$220,COUNTIF(Sheet1!$G$2:$G$220,"?*"))
I have then writen this in the ListFillRange in the properties of my combo box.
It works fine for one, but once i had made the second one and selected the site the first one will no longer let me search through.
I have used the same formulas on both but they originate from different sheets to see if this fixed the problem however that was unsuccessful. (the boxes are on different sheets) When i click on the next sheet after using the box on the first sheet, it still shows part of it as if it is crashing.
The boxes are independent so I'm not sure what to do next as i need to add another 3 on separate sheets.
I am also using this code for each box
Private Sub ComboBox1_Change()
ComboBox1.ListFillRange = "MList"
Me.ComboBox1.DropDown
End Sub
and similar for the other button but with a different range.
There is no need to use VBA for this, the Change Events specifically, if you just want to use and fill the combo boxes with Named Ranges.
The scenario I think you try to do is:
Create Named Ranges that will be the source of your combobox:
Fill the range with your data, select the range, Right Click, Select Define Name and give the range a name. MList in your case I believe.
Create Combobox:
Goto Developer Tab, Insert in your case ActiveX ComboBox, Draw it on your sheet, right click the ComboBox, select properties, find ListFillRange in properties and enter the name of the Named Range you created in step one
Repeat for Combobox 2, with the same or a different Named Range depending on what you try to do
Leave Design Mode
Boths Comboboxes can now be used to type in what you are looking for.
If this is not what you tried to do, please try edit your question and in detail try to explain what you try to do and what you like to accomplish by doing so.

Exporting Access Query to Excel

I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.
Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.
Any suggestions or ideas a very welcome.
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.
You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.
However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.
This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.
You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that. The VBA inside Acccess can call a function inside the VBA in Excel. That VBA could then copy the tabs as needed.
My idea would be a hybrid of Excel automation from Access and creating a template in Excel as well that would have a data table linked to your query.
To start create your data table in Excel. You can start three rows down and two columns to the right if you want or wherever. Go to your data tab and click access, find your db, choose your query you want to link to, choose table as the radio button but click properties next instead of ok, uncheck the enable background refresh, this part is critical ... under the definition tab in the connection string you will see a part that says Mode=Share Deny Write change that to Mode=Read, this will make sure that the query refreshes without errors from an MS Access VBA while the db is open and will keep your users from writing back to the db in case your query is a writeable query. Once you set that up you can adjust the table formatting however you choose from the table design tab and it will keep that formatting.
For the purposes of this we are going to assume you started the table in cell B4 ,and your named the worksheet CurrentDay, for purpose of the following VBA example be sure to replace that reference with your actual placement.
Next go back to Access and write your VBA first ensure that in your VBA window you have the reference to Microsoft Excel 12.0 Object Library is selected by going to Tools > References and selecting it from the alphabetical listing.
Create your sub as follows:
Sub query1_click()
Dim xl as Excel.Application
Dim wbk as Excel.Workbook
Dim wks as Excel.Worksheet
Dim RC as Integer
Dim CC as Integer
Set xl = New Excel.Application
Set wbk = xl.wbk.Open "X:\Filelocation\FileName.xlsx" 'name and path you saved the file you previously created
xl.Visible = True
'The above is not necessary but you may want to see your process work the first few times and it will be easier than going to task manager to end Excel if something fails.
RC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("B:B")) + 3 'This will count the rows of data in your table including your header so you can copy the data to another tab dynamically as the size of your table expands and shrinks we add 3 to it because we started at row 4 and we need the location of the last row of the record set.
CC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("4:4")) + 1 'This counts the header row and adds one space because we will use this as a location holder for our copy / paste function
Set wks = xl.wbk.Worksheets.Add
wks.Name = format(date(),"MM_dd_yy") 'this will name the tab with today's date... you can eliminate this step if you just want the sheets to be the generic Sheet1, Sheet2, etc.
With xl.wbk
.Worksheets("CurrentDay").Range(Cells(4,2),Cells(RC,CC)).Copy
.wks.PasteSpecial xlPasteValues 'This pastes the values so that the table links do not paste otherwise every tab would just refresh everyday.
.wks.PasteSpecial xlPasteFormats 'This gets your formatting.
.RefreshAll 'This will refresh your table
Wend
With xl
.Save
.Close False
.Quit
Wend
Set xl = Nothing
Set wbk = Nothing
Set wks = Nothing
End Sub
That should get you to have your data to not start on A1 of your sheets, save your old data each time, and automate the steps from access.

Copying specific rows from a sheet tab to another sheet tab by just clicking a button

I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button.
Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?
If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:
Sub Copybutton_Click()
Range("Copyend").value = Range("Copystart").value
Range("Copyend").visible = True
End Sub
If you have multiple named ranges with the same name, then add [Sheetname]. in front of the range, where Sheetname is the name of the sheet that the named range is in that you want to reference.
There are no native functions in Excel that will allow you to do this. You will need to write a macro and assign that to a button control (which you can drop onto your worksheet by using the Control Toolbox toolbar - View > Toolbars > Control Toolbox).
You would usually then assign the macro to that button by double-clicking the button (while it's still in Design View) and calling your macro in the newly-generated `CommandButton_Click` event. As Lance says, named ranges would be the easiest to work with.
To answer the last part of your question, programmatically copying a range doesn't copy the formatting or formula as well. It only takes the value of the cell. So regardless of whether your source range is hidden, the destination will not need to have its `visible` property explicitly set - the hidden attribute is ignored when copying.

Resources