Monday, November 7, 2016

Extracting Data using Cursor in VBA

Option Private Module
Option Explicit
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset, querystring, i As Integer, rowcount As Long
'get employeelis for Oracle Domain
Sub getempDetailsForOracle()
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
querystring = "Select tbemp.empCode,tbemp.empName from empDetails tbemp join tbldomainList tbdom on " _
& "tbemp.empDomainId=tbdom.domainId  where tbdom.domainId=8"
i = 1
rowcount = ThisWorkbook.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
If (rowcount > 1) Then
        ThisWorkbook.Sheets(1).Range("A2:B" & rowcount).ClearContents
End If
    conn.ConnectionString = "Data Source=empDetails;Initial Catalog=*;uid=*;pwd=*"
    conn.CursorLocation = adUseClient
    conn.Open
    rst.Open querystring, conn, adOpenStatic
        Do While Not rst.EOF
        i = i + 1
             ThisWorkbook.Sheets(1).Range("A" & i) = rst.Fields(0).Value
             ThisWorkbook.Sheets(1).Range("B" & i) = rst.Fields(1).Value
                rst.MoveNext
        Loop
        rst.Close
        conn.Close
        Set rst = Nothing
        Set conn = Nothing
End Sub

No comments:

Post a Comment