Monday, March 17, 2014

Methods of Reading Data from EXCEL Sheet -Using VBScript

Method #1
Datatable.Importsheet “path of the excel file.xls”, source sheet ID/Name, desination sheet ID/Name
Datatable.SetCurrentRow(1)  ‘Read Value from First Row
value = datatable.Value(parameterName,Sheet ID/Name)
‘To Read Value from All the rows
Datatable.Importsheet “path of the excel file.xls”, source sheet ID/Name, desination sheet ID/Name
For vRow = 1 To Datatable.GetRowCount
Datatable.SetCurrentRow(vRow)
value = datatable.Value(parameterName,Sheet ID/Name)
Next

Method #2
Dim objexcel, objWorkbook, objDriverSheet, columncount, rowcount
set objexcel = Createobject(“Excel.Application”)
Set objWorkbook = objExcel.WorkBooks.Open(“path of the file.xls”)
Set objDriverSheet = objWorkbook.Worksheets(“name of the sheet / Id of the sheet”)
columncount = objDriverSheet.usedrange.columns.count
rowcount = objDriverSheet.usedrange.rows.count
for i = 1 to colunmcount
columnname = objDriversheet.cells(i,1)
if columnname = knowncolumnname then
for j = 1 to rowcount
fieldvalue = objdriversheet.cells(j,i)
next
end if
next
Method #3
Function GetDataFromDB (strFileName, strSQLStatement)
Dim objAdCon, objAdRs
Set objAdCon = CreateObject(“ADODB.Connection”)
objAdCon.Open “DRIVER={Microsoft Excel Driver (*.xls)};DBQ=”&strFileName & “;Readonly=True”
If Err <> 0 Then
Reporter.ReportEvent micFail,”Create Connection”, “[Connection] Error has occured. Error : ” & Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs = CreateObject(“ADODB.Recordset”)
objAdRs.CursorLocation=3                        ‘ set the cursor to use adUseClient – disconnected recordset
objAdRs.Open strSQLStatement, objAdCon, 1, 3
MsgBox objAdRs.fields(4).name
While objAdRs.EOF=false
For i=0 to objAdRs.Fields.count
Msgbox objAdRs.fields(i)
Next
objAdRs.moveNext
Wend
If Err<>0 Then
Reporter.ReportEvent micFail,”Open Recordset”, “Error has occured.Error Code : ” & Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs.ActiveConnection = Nothing
objAdCon.Close
Set objAdCon = Nothing
End Function
Example
Set rsAddin = GetDatasFromDB(“C:Documents and SettingsgrameshDesktopLogin.xls”, “Select * from [Login$]“)

No comments:

Post a Comment