I'm attempting to extract a table of historical stock prices to bring into a an Excel worksheet. I'm currently using Excel for Mac so activex / com objects are not supported, which is why I have had to go this route. If I use a different URL it extracts the table information just fine, and visiting the URL directly in browser works fine, but if I try to extract historical price information Excel throws a VB error 1004.
HistoryURL = "URL:https://finance.yahoo.com/quote/AAPL/history?period1=1577836800&period2=1609459200&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true"
With .QueryTables.Add(Connection:=HistoryURL, Destination:=.Range("Z1"))
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
End With
What am I missing here?
Couldn't find a suitable way to do this with VBA so I enabled the Beta Channel updates for Excel which allowed me to start using the native StockHistory function.
I've done a bit of work with finnancial data/stock price data and I found the following API a lot easier to work with than yahoo's finance data. You can get historical stock price data, so feel free to check it out and see if it might work for your application. Finnancial API
Related
I have a script that opens an Excel spreadsheet and then goes to a specific sheet before running a macro. The problem is that this macro brings up different dialog boxes which require user input - I am trying to automate the process. I have tried to get rid of these boxes by using the following code:
import os
impor win32com.client
xl = win32com.client.Dispatch('Excel.Application')
xl = DisplayAlerts = False #Supposed to disable alert/messages/dialog boxes
wb = xl.Workbooks.Open(os.path.abspath('Test.xlsm'), ReadOnly = 0) #Opens spreadsheet
wb.Worksheets('Assets').Activate() #Activates correct sheet
wb.Application.Run('MxRunAction') #Runs macro
wb.Clost(True)
I have read on many threads that:
Application.DisplayAlerts = False
is supposed to fix this problem, yet this seems to do nothing if I substitue Application with xl for my case. Am I using it properly in this sense?
That would be the Application need to be closed
xl.DisplayAlerts = False
I have an Excel-based reporting tool that connects to an oracle database to run canned reports and return the results in a new spreadsheet. I don't have any problem connecting to the database or running my reports. Database credentials are provided via a userform each time a report is needed. I see this question asked in many different ways but no real answer so I'll try to be clear.
Current Behavior
User provides incorrect database credentials
System box pops up with fields for username, password, and server with "Ok" and "Cancel" button
Excel doesn't catch this as an error so I can't use normal error handling.
Desired Behavior
Excel catches the incorrect credentials reported back from the oracle database before the system message pops up
If that happens, I can present the user with my custom error message and branded userform.
I'm just trying to avoid the system message for user experience reasons. Should I try to authenticate with the database and assess the response? Any help would be appreciated! I'm not sure if there is any code I can share that would be helpful.
Updated with a code snippet and workflow:
User click Create Report button
User is presented with userform with 3 dropdowns
User picks application (let's call this variable app) from 1st dropdown
User picks report type (let's call this variable reportType) from 2nd dropdown
User picks report from (let's call this variable report) 3rd dropdown
User clicks Submit button
User provide username and password in second userform
User clicks Submit button
A few things to know about the code snippet below:
dbProvider is OraOLEDB.Oracle.
pw is provided by the user through the userform in step 7.
un is provided by the user through the userform in step 7.
database is stored in the macro itself by application on another tab. The macro looks up the databases for the respective application picked by the user.
wsData is just a tab in my spreadsheet where the result of the query is displayed.
userQuery is created based on the app, reportType, and report picked by the user. I have a few custom functions that build queries based on what the user picked. I don't have any issues with these and they run fine.
This is how Excel connects to the oracle database.
With wsData.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=" & dbProvider & ";Password=" & pw & ";User ID=" & un & ";Data Source=" & database, Destination:=wsData.Cells(lrData + 1, 1)).QueryTable
.CommandType = xlCmdSql
.CommandText = userQuery
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
This is the box that pops up that I'm trying to keep from popping up:
Oracle Box
I used to make pdf file from Access forms using this code:
DoCmd.OutputTo acOutputForm,"FR_PFMEAPrint2", acFormatPDF,"PFMEAPrint2.PDF", True
and I printed Excelforms with Portrait orientation in Access using this code:
Excel_App.ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True
and for landscape I used this code in Access:
Forms("FR_Print").Printer.Orientation = acPRORLandscape
DoCmd.PrintOut acPages, 1, 1, , 1
but I need to output Excel file to PDF landscape format via Vba Access Thanks
You have to set the property of Excel Sheet object like shown in the sample code snippet below:
Sheets(1).PageSetup.Orientation = xlLandscape
Pertinent to your case it will look like:
Excel_App.ActiveWindow.SelectedSheets(1).PageSetup.Orientation = xlLandscape
or you can iterate through the multiple Sheets and set their property in the loop. Also, FYI: you can use underlying xlLandscape value of 2.
Hope this will help.
I'm trying to set the orientation of data labels on a bar chart to vertical. Normally I'd find out how to do this by recording a macro, but for some reason it doesn't seem to generate any code. Is it possible to do?
I'm using Excel 2010.
Here is what recording the macro generated:
With Selection.TickLabels
.ReadingOrder = xlContext
.Orientation = xlDownward
End With
Hope this helps! :)
I am trying to combine multiple audit tables, and then filter the results into an excel sheet. The Union All and parameters make the query in excess of 1200 characters. It appears the string is truncated when running this. What recommendations can anyone make. I have no control over the database structure and am only reading foxpro free tables.
I am permitted table creation but can write into the excel sheet connecting to the datasource
An update to this is that I was able to extend the query string beyond 1800 characters and get data back. So I conclude I had syntax errors and the apparent truncation I mentioned was a failure in my string development in the scripting.
I posted an example of my connection code and that answer has disappeared, so I am not sure how to designate this a closed issue. There is NOT an apparent string length limit and that was my initial concern. Thanks for the contributions.
Can you not create a recordset with a superset of the desired data, then run a second query against that to do the final filtering?
Alternatively, and I'm not in any way familiar with FoxPro or your database privileges, could you create a stored procedure in the database and then just pass parameters to it?
Edit to add: I presume you're already giving your tables short names? (e.g. ...FROM Extremely_Long_Table_Name a WHERE...) If not, this could probably save you a pile of characters.
If it's a Union Query, as your question suggests, then you could break it up into each sub-query and run them one after the other.
I can hardly believe that the limit on your query string would be so small though. Where is your query being truncated? By VBA? by FoxPro? Can you copy/paste your generated query directly into a database client and see if it runs correctly?
After rewriting the query a number of ways, I have gotten the string length for the query beyond 1800 characters successfully. I have to conclude that my previous error was syntax although the vba error didn't give many clues.
The query string is built using controls on an excel sheet and accumulate in SQLstr. Apparent truncation was an error in my scripting the string creation. Once that was resolved then this:
With ActiveSheet.QueryTables.Add(Connection:=Array( _
"ODBC;DSN=myDB;Description=myDB;DATABASE=myDB;Trusted_Connection=YES"), Destination:=Range("A2"))
.CommandText = SQLstr
.Name = "Query from myDB"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
Thanks for the help because the responses indicating that it seemed unlikely to be a string length limit made me look at syntax instead.
I am still curious if there are query string size limits, if anyone knows.
Check for syntaxtical errors, I was getting similar errors, but it transpired to be syntax-error, there were some white-spaces missing where I concatenated my (2000+ chars long) query-string. Ensure that you have space before/after each concatenation-string, e.g.
qryStr = "SELECT name, tel, email" & _
" FROM MyTable;"
Note the space preceding the FROM clause (within double quotes). HTH. Eddie