Create a config file containing connection information then reference that connection - sql-server

I have an Excel sheet which contains VBA code assigned to a button.
Here is part of my VBA code:
Dim ConnectionStr As String
Dim sql As String
ConnectionStr = "Provider=SQLOLEDB.1;Password=ABCDEFG;User ID=xyz;Data Source=MyServer;Initial Catalog=NEW_DB"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;" & ConnectionStr), _
Destination:=Worksheets("Hidden").Range("$A$2")).QueryTable
.CommandType = xlCmdSql
.CommandText = "EXECUTE [dbo].[usp_one]"
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.ListObject.DisplayName = "Table_in_Hidden"
.Refresh BackgroundQuery:=False
End With
I don't want to show the connection string in a VBA macro, because someone may "peep" into it and discover our SQL Server password.
It seems one solution would be to create a config file containing the connection information and then to reference the config file in the VBA macro.

Anyway, VBA must finally get the password for the connection. No matter it's in a connection string or a config file.
And the connection is established by Excel via VBA, so the password (or a connection string, a config file, etc.) must be distributed with the excel sheet file.
Therefore, if someone has gotten the excel sheet and can use it normally, I don't think there be an effective way to prevent knowing the connection password.
If you wan't the excel sheet's users to make some changes on the database, you'd better not assign them the corresponding database privilege for the database user that the VBA code uses (if the database system supports user privilege limitation).

Related

Is there a way to "ping" an SQL Server via System.Data.SqlClient to see if it's online and ready for queries?

Is there a way to "ping" an SQL Server instance via System.Data.SqlClient to see if it's online and ready to accept queries?
The simple code below can be used to find the available SQL Servers on the LAN. But if the list of data sources is saved for later use, how can each instance be "pinged" to see if it's still available?
I could of course send a simple query to each instance, such as Use _master Select ##Version, but with a long list that might take a while. If there was some simple function such as SomeInstance.IsAvailable, that would be much better.
Dim sqlEnumInst As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
Dim sqlEnumData As System.Data.DataTable = sqlEnumInst.GetDataSources()
For Each row As DataRow In sqlEnumData.Rows
Dim srvn As String = row("ServerName").ToString
Dim insn As String = row("InstanceName").ToString
Dim svrStr As String = srvn & "\" & insn
Console.WriteLine(svrStr)
Next

With only the Select and View Definitions permission on a view, can SQL queries be sent from Excel without needing to type the query each time?

I have views that my users often only need to check for one particular person at a time. To do this, they do the following in Excel 365 desktop:
Open a blank workbook
Click on the 'Data' ribbon
Click 'Get Data'
Click 'From Database'
Click 'From SQL Server Database'
Fill in the 'Server' and 'Database' fields
In the advanced options, type SELECT * FROM [VEIWS].[VIEW_NAME] WHERE [EMP.ID] = '123456'
Click OK.
This is tedious for my users. If they want to check another person, they have to repeat the entire process. I'd love for them to just be able to use the query editor and change the only line that matters (see step 7), but they've only got the Select and View Definitions permission, which causes the query editor to complain. I'm afraid that I don't have the specific error message, but it's certainly to do with permissions.
Is there a less-repetitive way to do this from Excel? In an ideal world, I'd just make a sheet that lets them type in the EMP.ID immediately and then fetches the info. I think that it can be done with macros, but they're never my first choice and seem to require that I save passwords in the workbook.
Note that my users can't just fetch the entire view and filter it down in Excel. There are too many rows for Excel to handle.
I have no idea what permissions error you’re hitting, but people commonly use Windows credentials instead of Database credentials and get stuck. Power Query saves credentials on each computer, so you are relying on them signing in correctly. The first time someone connects to a data source, they are prompted for credentials. The default is for a Windows credential, and likely they need to enter a Database credential. If they get this wrong, they have to go into the Data Source settings to edit or clear the credential to fix it.
As far as changing the value in the SQL, you can easily have a parameter in Excel that changes the EMP.ID value in your query. Ken Puls has a nice write up on the process here. Reply back if you’re stuck.
You could use a SSAS Cube with a PivotTable in Excel with a filter on EMP.ID.
I guess it is not possible to change the query in Excel without Power Query Editor and I think it was not intended to do so (regulary).
If it does not need to be Excel you cloud just use SSMS or any similar alternative.
did you try to Un-tick the box that says "Require user approval for new native database queries" ?
you can set the ID as a parameter as suggested above... check my sample file for running an SQL query with a parameter. Sample File
also you can automatically refresh the worksheet with something like :
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("datachange")) Is Nothing Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
'Application.Goto Reference:="Tum_Santiyelerin_Satinalinan_Malzemeleri"
Range("EMP_ID").ListObject.QueryTable.Refresh BackgroundQuery:=False
ActiveWorkbook.RefreshAll
Application.EnableEvents = True
End Sub
I had a similar requirement in the past. My solution was to use the QueryTables object to send a query to the database using user-supplied data from a cell on the worksheet. It does use a macro, but I didn't have to save the credentials in the workbook.
This solution requires an ODBC driver for SQL Server.
(I seem to recall that I also had to check the references in Visual Basic - in toolbar Tools>References - but it was a while ago and I don't remember the exact details.)
Add the vb code below to a new workbook. Then if you enter the [EMP.ID] value in cell A1 of Sheet1 and run the macro 'ReadData', it will pull out the records and display them starting in cell A3.
Save the workbook as macro-enabled .xlsm and it can be shared with your users. (You could also assign the macro to a keyboard shortcut or command button to speed things up for your users.)
(This approach attempts to connect to the database using a trusted connection, i.e. using windows log-in credentials. I also use another database which requires separate credentials. I have another example below for that scenario.)
The vb code for the macro is below. Check the connection string that it has the correct driver and server IP address etc. and that the query string it reading the correct table.
Sub ReadData()
''' read database using filter supplied in cell A1
Dim ConnectionString As String
Dim QueryString As String
' Create connection string using credentials
ConnectionString = "ODBC; DRIVER={SQL Server}; SERVER=XX.XX.X.XXX; DATABASE=XXXXXXXXX; SCHEMA=dbo; REGION=yes;"
' Create query string to read data using value of cell A1
QueryString = "SELECT * FROM [VEIWS].[VIEW_NAME] WHERE [EMP.ID] = '" & Range("Sheet1!A1").Value & "'"
' The lines below can be un-commented if you get errors - it might help with debugging
'Range("Sheet1!C1").Value = ConnectionString
'Range("Sheet1!C2").Value = QueryString
' This code sends the query to the database and drops the results starting at cell A3
With Sheets("Sheet1").QueryTables.Add(Connection:=ConnectionString, _
Destination:=Range("Sheet1!A3"), Sql:=QueryString)
.RefreshStyle = xlOverwriteCells ' this stops excel from inserting new columns when the query is re-run
.Refresh False
End With
' Remove connections to avoid wasting memory
For Each con In Sheets("Sheet1").QueryTables
con.Delete
Next
End Sub
When the database requires different credentials
For this I created a user form to get the username and password, which I then incorporated into the connection string.
The steps I followed were:
In a new workbook, go to Visual Basic and create a new user form. Re-name it LoginForm
Create 2 text boxes on the form, named Username and Password. (You can also add labels and set the PasswordChar to '*' to make it look more like a login window.)
Create a command button ('OK' or 'Done'). Right click on it and select View Code. Enter the line Me.Hide in the code window so it looks like:
Private Sub CommandButton1_Click()
Me.Hide
End Sub
The vb code for the macro changes to :
Sub ReadData()
''' read database using filter supplied in cell A1
Dim ConnectionString As String
Dim QueryString As String
' First time you run, need to show form to get credentials
If LoginForm.Username = "" Or LoginForm.Password = "" Then LoginForm.Show
' Create connection string using credentials
ConnectionString = "ODBC; DRIVER={SQL Server}; SERVER=XX.XX.X.XXX; DATABASE=XXXXXXXXX; SCHEMA=dbo; REGION=yes; uid=" _
& LoginForm.Username & "; pwd=" & LoginForm.Password
' Create query string to read data
QueryString = "SELECT * FROM [VEIWS].[VIEW_NAME] WHERE [EMP.ID] = '" & Range("Sheet1!A1").Value & "'"
' The lines below can be un-commented if you get errors - it might help with debugging
'Range("Sheet1!C1").Value = ConnectionString
'Range("Sheet1!C2").Value = QueryString
' This code sends the query to the database and drops the results starting at cell A3
With Sheets("Sheet1").QueryTables.Add(Connection:=ConnectionString, _
Destination:=Range("Sheet1!A3"), Sql:=QueryString)
.RefreshStyle = xlOverwriteCells ' this stops excel from inserting new columns when the query is re-run
.Refresh False
End With
' Remove connections to avoid wasting memory
For Each con In Sheets("Sheet1").QueryTables
con.Delete
Next
End Sub
Now, the first time the user runs the code, it will prompt them for username and password, but for the rest of their session it will keep using these values. They will not be saved when the workbook is closed. (If the macro hits an error they will probably be asked for credentials again next time it is run).
Hopefully this helps you. I did this work some time ago and I may have forgotten if there were any other set-up requirements needed.

Disable SQL Server Login pop up for other users

Does anyone know how do I get rid of below popping up on other users computer who will only be using the spreadsheet as read-only file?
The data in the spreadsheet comes from a SQL query, and has OLE DB refresh enabled when opening the file. I will need to send this spreadsheet out to internal as well to external people but I don't want them to have this pop up appear on their screen.
The spreadsheet is collecting and updating data every time its opened and hence it is required to remain connected. What are my other options? There are more than 15 reports set up in the spreadsheet which will be sent out once every week internally as well externally.
I’m using the below VBA script to refresh the spreadsheet. Is there any code I could use in the script that will save the workbook and remove the SQL connection?
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oExcel.DisplayAlerts = False
oExcel.AskToUpdateLinks = False
oExcel.AlertBeforeOverwriting = False
Set oWorkbook = oExcel.Workbooks.Open("file path.xlsx")
oWorkbook.RefreshAll
oWorkbook.Save
oExcel.Quit
Set oWorkbook = Nothing
Set oExcel = Nothing

[VB.NET][ACCESS] How do I check for if a database exists?

I cant find anything online to help.
I want to create a table if it doesnt already exist, or populate a listbox with what is stored in said table if it DOES exist. All I have so far is the populate and create table subroutines, but have no idea how to check the database so far.
Thank you
Checking if an MSAccess DATABASE exists or not is pretty simple because it is just a single file. So using File.Exists is enough
Suppose that your MDB file is
Dim accessFilePath = "D:\temp\myDatabase.mdb"
If File.Exists(accessFilePath) Then
... file exists
End if
Of course getting the content of the file (in terms of TABLES and QUERY) is a different thing and requires to open the connection and get the SCHEMA informations
Dim cnnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & accessFilePath
Using con = new OleDbConnection(cnnString)
con.Open()
Dim schema = con.GetSchema("Tables")
For Each row As DataRow in schema.Rows
Console.WriteLine(row.Field(Of String)("TABLE_NAME"))
Next
End Using
See how GetSchema works and what are its possible parameters and results

Excel data connection to SQL dB error

I crafted a macro in an Excel workbook to extract a subset of data from a SQL database based on user input.
The macro prompts the user for a parameter input and inserts that parameter into a ready-made stored procedure configured into a an Excel data connection - see below for my vba:
Sub RefreshDBQuery()
Dim Val As Integer
Application.ScreenUpdating = False
Worksheets("Adjustable CF").Select
Val = InputBox("Enter valid 4 digit number", , 1907)
Sheets("TestData").Visible = True
Worksheets("TestData").Select
Worksheets("TestData").Range("A1").Select
ActiveCell.Value = Val
With ActiveWorkbook.Connections("MacroExtraction 2Server").OLEDBConnection
.CommandText = "EXEC dbo.prV_FlowExtract '" & Range("A1").Value & "'"
End With
ActiveWorkbook.Connections("MacroExtraction 2Server").Refresh
Sheets("TestData").Visible = False
End Sub
When I run it - it works fine and additionally, since it's modifying an existing data connection ( the one I previously configured), I notice a odc file in a folder called "My Data Sources" under My Documents:
However, when I send this workbook over to a colleague to run the macro and to extract data - the macro is able to run up to a point, and she receives an error:
I ask her to open up the folder "My Data Sources" and I don't see an odc file:
My question is: what am I missing? Or rather what is my colleague missing in order to get her macro to work on her local machine?
I checked with the dB administrator who said that she has the permissions necessary to access the server, so that's why I am picking on the lack of the odc as a cause for my concern. Should I copy my odc file and send it to her to copy into her Data Sources folder? Should I rewrite the macro and re-setup the data connection on her local machine? Anyone with experience to comment would be much appreciated! Thanks!
The macro alone does not contain all the necessary info (server name, for example?). Try running "NewSQLServerConnection.odc" in you colleague's my data sources location, complete the necessary data, make sure the connection name is the same as in your macro, and then the macro should work.
Hope this helps!

Resources