Saturday, January 19, 2013

How to retrieve data from Excel file using ADODB

The below code retrieves data from Sheet1 from an Excel file using ADODB.

Both the connection strings specified here works.

Set oCmd=createobject("ADODB.Command")
Set oRS=createobject("ADODB.RecordSet")

sCon="Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=D:\Programming Samples\QTP\SampleXL.xls;"
'sCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Programming Samples\QTP\SampleXL.xls;Extended Properties=""Excel 8.0;"""
sQry="select * from [Sheet1$]"

oCmd.ActiveConnection = sCon
oCmd.CommandText=sQry
Set oRS=oCmd.Execute
While not oRS.EOF
    print oRS.Fields(1).Value
    oRS.MoveNext
Wend

oRS.Close

Set oCmd=nothing
Set oRS=nothing

No comments: