Thursday, February 28, 2013

Display Sql-server Data into Excel Using VBA


-->
Display Sql-server Data into Excel Using VBA , Working code

Private Sub CommandButton1_Click()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim results As ADODB.Recordset
Dim sSQL As String
Dim lRow As Long, lCol As Long
sConnString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=devdb;Data Source=sqlserverdv1;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=USER-PC;Use Encryption for Data=False;Tag with column collation when possible=False"
Set adoCN = CreateObject("ADODB.Connection")
adoCN.Open sConnString

    sSQL = "select top 10 * from tempdata"
Set results = adoCN.Execute(sSQL)
   
    
    
    For Each f In results.Fields
      'Debug.Print f.Name & " " & f
      ActiveSheet.Range("A1").CopyFromRecordset results
    Next
adoCN.Close
Set adoCN = Nothing


End Sub


No comments: