Skip to content

Instantly share code, notes, and snippets.

@addohm
Created November 30, 2018 04:11
Show Gist options
  • Save addohm/e5f8c450f9b6d354886a9a9c143a0399 to your computer and use it in GitHub Desktop.
Save addohm/e5f8c450f9b6d354886a9a9c143a0399 to your computer and use it in GitHub Desktop.
VBA Read DB Settings in from file
Attribute VB_Name = "dbSettings"
Public Function ConnectionString() As String
Dim sqlSettings() As Variant
Dim SqlServer, SqlDBName, SqlUserName, SqlPassword As String
'read in sql parameters
sqlSettings = getSettings
'move parameters into readable variable names
SqlServer = sqlSettings(0)
SqlDBName = sqlSettings(1)
SqlUserName = sqlSettings(2)
SqlPassword = sqlSettings(3)
'construct connection string
ConnectionString = "Provider=sqloledb;data source=" & SqlServer _
& ";initial catalog=" & SqlDBName _
& ";user id=" & SqlUserName _
& ";password=" & SqlPassword
End Function
Private Function getSettings() As Variant
Dim myFSO As New FileSystemObject
Dim path As String
Dim fileName As String
Dim sqlSettings() As Variant
path = "C:\path\to\file\"
fileName = "dbSettings.ini"
i = 0
x = 0
Set fso = myFSO.OpenTextFile(path + fileName)
'ignore comments (begind with hyphen)
'accept setting as variable in array (begins after trailing space after colon)
Do Until fso.AtEndOfStream
txt = fso.ReadLine
ReDim Preserve sqlSettings(i)
For x = 1 To Len(txt)
If Mid(txt, x, 1) = "-" Then
Exit For
End If
If Mid(txt, x, 1) = ":" Then
sqlSettings(i) = sqlSettings(i) + Mid(txt, x + 2, Len(txt))
Exit For
End If
Next
i = i + 1
Loop
getSettings = sqlSettings
fso.Close
LogDiagnosticsMessage "Loaded SQL settings from file"
End Function
Server Name: servername
Database Name: databasename
User Name: user
Password: pass
--Database Settings v1.1
--Lines that begin with '-' are ignored
--Space required after colon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment