Catching wrong database credentials using VBA to oracle database - excel

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

Related

Excel not extracting table of historical stock prices from Yahoo Finance

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

Suppress the message "Getting Data..." when importing from ODBC..?

In Excel 2007, when importing data via SQL/ODBC, it displays the message "Getting data" in the top-left cell of the import range. This occurs whether the query is run from the GUI or from VBA.
Can this message be suppressed..??? There seem to be no settings for it, either in the GUI or the VBA object properties of the WorkbookConnection, ODBCConnection, ListObject, or QueryTable.
I would like to create a customized "please wait" message with an animation, but the "Getting Data" message creates a visual conflict.
I tried the following, but it didn't suppress the message:
xl.ScreenUpdating = False
xl.DisplayAlerts = False
ExternalData_1: Getting Data...
Try disabling BackgroundQuery parameter:
With Selection.QueryTable
.BackgroundQuery = False
End With

VBA - Update Linked Table of an Access file from Excel

I am trying to change the linked table address from an Access file "Hey.accdb" using VBA coding from an Excel file.
I've coded the script below in my Excel file and it prompts the error "Object required" when I run it. Can someone please help me with this problem. I've been staring at it for too long. Thanks.
Sub RunMacroinAccesswithPara2()
Set Db = CreateObject("Access.Application")
Db.OpenCurrentDatabase "D:\Database1\Hey.accdb"
Db.Visible = True
Db.AutomationSecurity = msoAutomationSecurityLow
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="V:\Reporting\Quarterly\2018Q2\JP\Data\04\Database\Valuation_Database.mdb", _
ObjectType:=acTable, _
Source:="Valuation_Database_Adjusted", _
Destination:="Valuation_Database_Adjusted"
End Sub
DoCmd belongs to the Access application object.
So use
Db.DoCmd.TransferDatabase ' etc.
Edit
To update the link, you need the TableDef object, set its .Connect property and run .RefreshLink.
See Linked table ms access 2010 change connection string

Confirm prompt using Powershell

I'm using powershell to automate a daily task. It is essentially a macro to refresh data linked to an external source and then sends an email out. The issue is that Excel automatically prompts for username/password whenever it tries to refresh the data. I did some digging and it can not be bypassed by setting DisplayAlert = False and cannot be changed from Excel's settings. My credentials are saved so what I really need to do is to have a script to press on "Enter".
I have the following set up currently: using Windows Scheduler, I first launch a Powershell script that'll open up Excel and run the macro to refresh the data. The macro will be stuck when Excel prompts for credentials. I have a second task which is scheduled to run 2 minutes after the first one and its purpose is to press on "Enter" to get rid of the prompt.
I have tried a couple of scripts for the second task but I just can't seem to get it right.
What I have tried is as follows:
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate("Windows Security")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
and
$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Any idea on how I can bypass/accept the prompt?
Thanks in advance.
We use a solution slightly different from what you already tried. Maybe it is in the details...
[void] [System.Reflection.Assembly]::LoadWithPartialName
("'Microsoft.VisualBasic")
[Microsoft.VisualBasic.Interaction]::AppActivate("Windows Security")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Please share the data link for more details, however, I would simply recreate the data link programmatically if indeed there is a reason why the pass & login can be saved e.g. a macro accepting pass and login
If it's a SQL connection then it would look something like this:
Sub Recreate(serverInstance as String, database as String, userId as String, password as String)
sConn = "OLEDB;Provider=SQLOLEDB;Data Source=" & _
serverInstance & ";Initial Catalog=" & database & _
";User ID=" & userId & ";Password=" & password & ";"
Set qt = wks.QueryTables.Add(Connection:=sConn, _
Destination:=Target)
With qt
.CommandType = xlCmdSql
.CommandText = sql
.Name = sName
.RefreshStyle = xlOverwriteCells
.Refresh BackgroundQuery:=False 'Execute SQL
End With
End Sub

Query string length limit in vba?

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

Resources