We can change this function to accept both Access and SQL Server:
VB Code:
  1. Const ODBC_ADD_SYS_DSN = 4       'Add System data source
  2. Const ODBC_ADD_DSN = 1       'Add User data source
  3. Const ODBC_CONFIG_SYS_DSN = 5    'Configure (edit) data source
  4. Const ODBC_REMOVE_SYS_DSN = 6    'Remove data source
  5.  
  6. Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal _
  7.    hwndParent As Long, ByVal fRequest As Long, ByVal _
  8.    lpszDriver As String, ByVal lpszAttributes As String) As Long
  9.  
  10. Public Enum enumDSN_Type
  11.     eUserDSN = ODBC_ADD_DSN
  12.     eSystemDSN = ODBC_ADD_SYS_DSN
  13. End Enum
  14.  
  15. Public Enum enumDBType
  16.     eACCESS = 0
  17.     eSQL_SERVER = 1
  18. End Enum
  19.  
  20. Public Function CreateDSN(p_DSNName As String, p_DSNType As enumDSN_Type, _
  21.                     p_DBType As enumDBType, p_strDatabase As String, _
  22.                     Optional p_strServer As String = "", _
  23.                     Optional p_strUser As String = "", _
  24.                     Optional p_strPassword As String = "") As Boolean
  25.     Dim lngRetVal
  26.     Dim strDriver As String
  27.     Dim strAttributes As String
  28.    
  29.     CreateDSN = False
  30.      
  31.     Select Case p_DBType
  32.         Case eACCESS
  33.             strDriver = "Microsoft Access Driver (*.mdb)" & Chr$(0)
  34.             strAttributes = "DSN=" & p_DSNName & Chr$(0)
  35.             strAttributes = Attributes & "Uid=Admin" & Chr$(0) & "pwd=" & Chr$(0)
  36.             strAttributes = Attributes & "DBQ=" & pDBPath & Chr$(0)
  37.         Case eSQL_SERVER
  38.             strDriver = "SQL Server"
  39.             strAttributes = "SERVER=" & p_strServer & Chr$(0)
  40.             strAttributes = strAttributes & "DESCRIPTION=" & Chr$(0)
  41.             strAttributes = strAttributes & "DSN=" & p_DSNName & Chr$(0)
  42.             strAttributes = strAttributes & "DATABASE=" & p_strDatabase & Chr$(0)
  43.             strAttributes = strAttributes & "UID=" & p_strUser & Chr$(0)
  44.             strAttributes = strAttributes & "PWD=" & p_strPassword & Chr$(0)
  45.              
  46.     End Select
  47.  
  48.     lngRetVal = SQLConfigDataSource(0, p_DSNType, strDriver, strAttributes)
  49.    
  50.     'If the Return Value 1 then
  51.     'DataSource is created succesefully
  52.     'otherwise it has falied
  53.     CreateDSN = lngRetVal
  54. End Function
Then you can call it like this:
VB Code:
  1. Private Sub Command1_Click()
  2.     Call CreateDSN("YourDSN", eSystemDSN, eSQL_SERVER, "YourDatabase", "ServerName", "sa")
  3. End Sub