Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have created two forms in excel VBA , First form for list available sql servers in a combo box and login with selected sql server . After connecting sql server, in the second form it has to list all the database names in one combo box and select the a particular database in another combo box it has to show table name for the respective database.

Here I have completed the first form , but i dont know how to work in the second form to list the database name and table name.

Below code i used to show server list and to connect the database, i know the query to list dtabase and tables but i want to do that from the vb userform..new to vb coding..jus need help on this..
VB
Private Sub UserForm_Activate()
Dim i As Integer
Dim oNames As SQLDMO.NameList
Dim oSQLApp As SQLDMO.Application

Set oSQLApp = New SQLDMO.Application
Set oNames = oSQLApp.ListAvailableSQLServers()

srvname.Clear
For i = 1 To oNames.Count
    srvname.AddItem oNames.Item(i)
Next i

End Sub

Private Sub CommandButton1_Click()
Dim myconn As ADODB.Connection
Dim rec As ADODB.Recordset
Dim canConnect As Boolean
Dim strSQL As String

Set myconn = New ADODB.Connection
Set rec = New ADODB.Recordset
strCS = "Driver=SQLOLEDB;" & _
    "Data Source=" & srvname.Value & ";" & _
    "Uid=" & uname.Value & ";" & _
    "Pwd=" & pwd.Value & ";" & _
     "trusted connection = yes;"
myconn.ConnectionString = strCS
myconn.Open Chr(34) & strCS & Chr(34)
If myconn.State = adStateOpen Then
    canConnect = True
    MsgBox "connected to server"
Else
    MsgBox "Invalid username & password"
End If

SelectTable.Show
End Sub

Please help me to do this ...

Thanks in advance

Sathish
Posted
Updated 15-Aug-11 8:36am
v3
Comments
Maciej Los 15-Aug-11 14:24pm    
Always use "Improve question" to make changes in the text.
I have made some changes: was changed the title of question (was: Connecting to SQL Server), were changed tags. Now is much better.

To enumerate databases, you need to "ask" your sql server ;) like this:
SQL
SELECT name FROM SYSDATABASES

The output:
master<br />
database1<br />
database2<br />
database3


It's probably Access application, so... (your) code after changes (with error handlers):
VB
Private Sub UserForm_Activate()
Dim i As Integer
Dim oNames As SQLDMO.NameList
Dim oSQLApp As SQLDMO.Application

On Error GoTo Err_UserForm_Activate

Set oSQLApp = New SQLDMO.Application
Set oNames = oSQLApp.ListAvailableSQLServers()
srvname.Clear
For i = 1 To oNames.Count
    srvname.AddItem oNames.Item(i)
Next i

Exit_UserForm_Activate:
    On Error Resume Next
    Set oSQLApp = Nothing
    Set oNames = Nothing
    Exit Sub

Err_UserForm_Activate:
    MsgBox Err.Description, vbExclamation, "Err no. " & Err.Number
    Resume Exit_UserForm_Activate

End Sub


VB
Private Sub CommandButton1_Click()
Dim myconn As ADODB.Connection
Dim rec As ADODB.Recordset
Dim canConnect As Boolean
Dim strSQL As String

On Error Goto Err_CommandButton1_Click

Set myconn = New ADODB.Connection
Set rec = New ADODB.Recordset

strCS = "Driver=SQLOLEDB;" & _
    "Data Source=" & srvname.Value & ";" & _
    "Uid=" & uname.Value & ";" & _
    "Pwd=" & pwd.Value & ";" & _
    "trusted connection = yes;"
myconn.ConnectionString = strCS
myconn.Open Chr(34) & strCS & Chr(34)

If myconn.State = adStateOpen Then
    canConnect = True
    MsgBox "connected to server"
Else
    MsgBox "Invalid username & password"
End If

SelectTable.Show


Exit_CommandButton1_Click:
    On Error Resume Next
    rec.Close 'always close recordset object
    Set rec = Nothing
    myconn.Close 'always close connection!
    Set myconn = Nothing
    Exit Sub

Err_CommandButton1_Click:
    MsgBox Err.Description, vbExclamation, "Err no. " & Err.Number
    Resume Exit_CommandButton1_Click
End Sub


VB
Private Sub UserForm_Activate()
Dim myconn As ADODB.Connection
Dim rec As ADODB.Recordset
 
On Error GoTo Err_UserForm_Activate
 
Set myconn = New ADODB.Connection
'replace uname.Value and pwd.Value with constant value or get them from loaded form like this:
'below code works for me: 
strCS = "Provider=SQLOLEDB;" & _
        "Data Source=server_name;" & _
        "Uid=user_name;" & _
        "Pwd=user_wd;" & _
        "trusted connection = yes;"
myconn.ConnectionString = strCS
myconn.Open strCS
 
Set rec = New ADODB.Recordset
With rec
    .ActiveConnection = myconn
    .CursorLocation = adUseClient
    .CursorType = adOpenDynamic
    .LockType = adLockOptimistic
    .Source = "SELECT name" & vbCr & _
                "FROM [master].[dbo].[sysdatabases]" & vbCr & _
                "where name not in " & _
                "('master','tempdb','model','msdb','pubs','Northwind')"
    .Open
    Do While Not .EOF
        DBName.AddItem .Fields("Name").Value
        .MoveNext
    Loop
End With
 
Exit_UserForm_Activate:
    On Error Resume Next
    rec.Close
    Set rec = Nothing
    myconn.Close
    Set myconn = Nothing
    Exit Sub
 
Err_UserForm_Activate:
    MsgBox Err.Description, vbExclamation, "Err. no. " & Err.Number
    Resume Exit_UserForm_Activate
End Sub
 
Share this answer
 
v3
Comments
sathish nagulan 16-Aug-11 2:55am    
As a DBA i know the query, but in VBA my second form i used this query im getting error like datasource not found, but in my first form i connected to sql.
Maciej Los 16-Aug-11 13:46pm    
Show me the code of second form.
sathish nagulan 17-Aug-11 1:52am    
Private Sub UserForm_Activate()
Dim rec As ADODB.Recordset
Set rec = New ADODB.Recordset

With rec

.ActiveConnection = myconn
.Open "select name from sysdatabases where name not in('master','tempdb','model','msdb','pubs','Northwind')"
DBName.AddItem
.Close

End With
myconn.Close
Set rec = Nothing
Set myconn = Nothing
End Sub
Maciej Los 17-Aug-11 11:33am    
If the code is complete, i supose the error is in the line: .ActiceConnection = myconn, because object myconn have been declared only in the first form, so... in the second form it is not visible. Add the declaration of myconn and set it (as you made in the first form) and you'll find solution. If not, give me a sign (reply to my answer), and i'll try to help you again.

Read more abut scope variables^
sathish nagulan 18-Aug-11 2:02am    
This is to list all the available SQlServers in a combo box

Private Sub UserForm_Activate()
Dim i As Integer
Dim oNames As SQLDMO.NameList
Dim oSQLApp As SQLDMO.Application

Set oSQLApp = New SQLDMO.Application
Set oNames = oSQLApp.ListAvailableSQLServers()

srvname.Clear
For i = 1 To oNames.Count
srvname.AddItem oNames.Item(i)
Next i

End Sub

After selecting the SQL Server this below code to login to the server

Private Sub CommandButton1_Click()
Dim myconn As ADODB.Connection
Dim rec As ADODB.Recordset
Dim canConnect As Boolean
Dim strSQL As String

Set myconn = New ADODB.Connection
Set rec = New ADODB.Recordset
strCS = "Driver=SQLOLEDB;" & _
"Data Source=" & srvname.Value & ";" & _
"Uid=" & uname.Value & ";" & _
"Pwd=" & pwd.Value & ";" & _
"trusted connection = yes;"
myconn.ConnectionString = strCS
myconn.Open Chr(34) & strCS & Chr(34)
If myconn.State = adStateOpen Then
canConnect = True
MsgBox "connected to server"
Else
MsgBox "Invalid username & password"
End If

SelectTable.Show
End Sub

After login to the server below code to display the database names and list the table names in two combo box based on the selected database
for this i need a code..i posted here what i would have tried.

Private Sub UserForm_Activate()
Dim rec As ADODB.Recordset
Dim myconn As Connection

Set rec = New ADODB.Recordset

With rec

.ActiveConnection = myconn
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Source = "select name from sysdatabases where name not in('master','tempdb','model','msdb','pubs','Northwind')"
Do While Not rec.EOF And Not rec.BOF
DBName.AddItem (rec.Fields("Name").Value)
'rec.MoveNext() = 1
Loop


'.Open

End With
'rec.Close
Set rec = Nothing
'myconn.Close
Set myconn = Nothing
End Sub
You can use for example sys.databases[^] to list the databases and sys.tables[^] to list the tables in the selected database.
 
Share this answer
 
Comments
sathish nagulan 12-Aug-11 9:17am    
Below code i used to show server list and to connect the database, i know the query to list dtabase and tables but i want to do that from the vb userform..new to vb coding..jus need help on this..

Private Sub UserForm_Activate()
Dim i As Integer
Dim oNames As SQLDMO.NameList
Dim oSQLApp As SQLDMO.Application
Set oSQLApp = New SQLDMO.Application


Set oNames = oSQLApp.ListAvailableSQLServers()
srvname.Clear
For i = 1 To oNames.Count
srvname.AddItem oNames.Item(i)
Next i

End Sub


private Sub CommandButton1_Click()

Dim myconn As ADODB.Connection
Dim rec As ADODB.Recordset
Dim canConnect As Boolean
Dim strSQL As String



Set myconn = New ADODB.Connection
Set rec = New ADODB.Recordset

strCS = "Driver=SQLOLEDB;" & _
"Data Source=" & srvname.Value & ";" & _
"Uid=" & uname.Value & ";" & _
"Pwd=" & pwd.Value & ";" & _
"trusted connection = yes;"

myconn.ConnectionString = strCS
myconn.Open Chr(34) & strCS & Chr(34)


If myconn.State = adStateOpen Then
canConnect = True

MsgBox "connected to server"
Else
MsgBox "Invalid username & password"

End If
SelectTable.Show

End Sub
Wendelius 12-Aug-11 9:33am    
Mohammad hassani 12-Dec-17 3:02am    
Hello All
which refrence should use for this line;

Dim oNames As SQLDMO.NameList
Dim oSQLApp As SQLDMO.Application

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900