Showing posts with label Excel. Show all posts
Showing posts with label Excel. Show all posts

Sunday, March 19, 2017

Handling multi-dimensional array in vbscript

Was trying to build excel data provider, which can be used for Test Complete and QTP scripts. Created a VBScript to keep all excel contents into a multi-dimensional array.

Problem
Declared array with lower limits and then used ReDim to fix with right count. But I was able to retrieve the data only upto the initial array size.

Solution:
Tried different ways. Then declared array without any size as given in below code.

Code:
'------------------------------------------------------------------------- ' File : ExcelReadByArrays.vbs ' Author : PalaniSelvam Thillaiappan ' Purpose : To read the given sheet contents . '------------------------------------------------------------------------- '' Usage '' cscript D:\MyCode\qtp_uft\ExcelReadByArrays.vbs '' test data: D:\MyCode\qtp_uft\testMyApp_1.xlsx '******** Variables Declaration Dim gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex Dim gsLogFile Dim arrExcelData() 'as all Rows data '''Dim arrExcelData(5, 5) 'as all Rows data giSheetIndex = 1 gsExcelFile = "D:\MyCode\qtp_uft\testMyApp_1.xlsx" '' Working fine, but array size should be given properly ExcelDataRead gsExcelFile, giSheetIndex, arrExcelData PrintArrays arrExcelData '-------------------------------------- ' Method : ExcelDataRead ' Author : PalaniSelvam Thillaiappan ' Purpose : Read all the contents from Excel sheet and write into log file ' Parameters: sExcelFile - String, contains the Excel file ' : iSheetIndex - Integer, Value for Sheet Index '-------------------------------------- Sub ExcelDataRead(sExcelFile, iSheetIndex, ByRef arrExcel) Dim sExcelPath 'As Variant 'Excel file '********** Excel object declaration **********' ' Excel Application object Dim objExcel 'As Excel.Application Dim objXLWorkbooks 'As Excel.Workbooks Dim objXLWorkbook 'As Excel.Workbook Dim WorkSheetCount 'As Variant 'Work sheets count in a excel Dim CurrentWorkSheet 'As Excel.Worksheet ' Current worksheet Dim objCells 'As Excel.Range Dim objCurrentCell 'As Variant Dim objFont 'As Variant ' Result contents Dim sCellText 'As Variant Dim sFontName 'As Variant Dim sFontStyle 'As Variant Dim iFontSize 'As Variant Dim iCellTextColorIndex 'As Variant Dim iCellInteriorColorIndex 'As Variant Dim sResult 'As Variant Dim sChartFile 'As String ' Row and Col integer variables Dim iUsedRowsCount 'As Integer Dim iUsedColsCount 'As Integer Dim iTop, iLeft 'As Integer Dim iRow 'As Integer 'Row item Dim iCol 'As Integer 'Col item Dim iCurRow 'As Integer Dim iCurCol 'As Integer Dim arrColList 'As Array - Column Name If (sExcelFile = "") Then sExcelPath = "D:\MyCode\qtp_uft\testMyApp_1.xlsx" Else sExcelPath = sExcelFile End If If (iSheetIndex = "") Then iSheetIndex = 2 End If Set objExcel = CreateObject("Excel.Application") objExcel.Workbooks.Open sExcelPath, False, True On Error Resume Next WorkSheetCount = objExcel.Worksheets.Count Set objXLWorkbook = objExcel.ActiveWorkbook 'objXLWorkbook.RunAutoMacros Set CurrentWorkSheet = objExcel.ActiveWorkbook.Worksheets(iSheetIndex) 'iSheetIndex worksheet iUsedRowsCount = CurrentWorkSheet.UsedRange.Rows.Count iUsedColsCount = CurrentWorkSheet.UsedRange.Columns.Count iTop = CurrentWorkSheet.UsedRange.Row iLeft = CurrentWorkSheet.UsedRange.Column CurrentWorkSheet.UsedRange.Columns.AutoFit() ' Cells object CurrentWorkSheet.Cells.Activate ReDim Preserve arrExcel(iUsedRowsCount, iUsedColsCount) ''ReDim arrColList(iUsedColsCount) For iRow = iTop To iUsedRowsCount '(iUsedRowsCount - 1) 'Read All Columns For iCol = iLeft To iUsedColsCount '(iUsedColsCount - 1) sResult = "" Set objCurrentCell = CurrentWorkSheet.Cells(iRow, iCol) sCellText = objCurrentCell.Text sResult = "Reading Cell {" & CStr(iRow) & ", " & CStr(iCol) & "}^" & sCellText & "^" WScript.echo sResult Set objCurrentCell = Nothing arrExcel (iRow-1, iCol-1) = sCellText Next Next ' This will prevent Excel from prompting us to save the workbook. objExcel.ActiveWorkbook.Saved = True Set CurrentWorkSheet = Nothing 'objExcel.Worksbooks.Close objExcel.Quit ''Set CurrentWorkSheet = Nothing Set objExcel = Nothing 'MsgBox "Read Completed.", vbOKOnly, "Exec Over" Exit Sub ErrorHandler1: 'MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description 'Err.Clear ' Clear the error. End Sub '' To display given array Sub PrintArrays( arrList) '' To Print all list items Dim aValue 'array item ==> dictionary Dim aItem 'dictionaly item ==> key-pair value Dim iRow Dim iCol WScript.echo "Array Rows Count: ",UBound (arrList, 1) '' First Array WScript.echo "Array Columns Count: ",UBound (arrList, 2) ''Second Array For iRow =LBound(arrList) to UBound (arrList)-1 For iCol=LBound(arrList,2) to UBound (arrList,2)-1 aValue = arrList(iRow, iCol) WScript.echo iRow, iCol, " Value:", aValue Next Next End Sub



Saturday, January 16, 2010

MSN Money Quotes

Few months back, I was searching a solution, which can get the current stock value for the given quote. I did not find proper solution to get current quote. I have done few VBA procedures in Excel, to do few more calculations after getting current stock quote.

I found Microsoft's Excel 2003/2002 Add-in: MSN Money Stock Quotes. It can be installed with Excel 2007 version also. This Add-in is very useful to the people, who wish to maintain or track their stock investments. It is used only for US stock markets. Microsoft provides better online help to this addin as MSN MoneyCentral Stock Quotes help.

However I cannot use this add-in for NSE or BSE markets. I used selenium to retrieve the quote from net.

Monday, December 8, 2008

Closing Excel instance by VBScript

We have a test suite for Excel plug-in. Silktest built-in function does not work for Excel 2007. It is working fine for Excel 2003. Silktest is unable to close the Excel 2007 instance. We used Taskkill to kill the excel. It has created few other issues. I was looking for alternative solution. So I decided to write a vb script and got success. I have given the code below.

VBS code - To close Excel

'------------------------------------------------------------------------- ' File : CloseExcel.vbs ' Author : Palani ' Purpose : To close the excel, if it is already opened. ' '' Revision History: ''$Log: CloseExcel.vbs,v $ '' '------------------------------------------------------------------------- '' Usage '' cscript D:\rpm_scripts_palani\tools\CloseExcel.vbs '' cscript CloseExcel.vbs '******** Variables Declaration Dim gsLogFile '******** Function calls call CloseExcelApps () '-------------------------------------- ' Method : CloseExcelApps ' Author : T. Palani Selvam ' Purpose : Close Excel application. ' Parameters: - Nil ' Returns : - Nil ' Caller : - Nil ' Calls : - Nil '-------------------------------------- Sub CloseExcelApps() Dim sExcelPath 'As Variant 'Excel file '********** Excel object declaration **********' ' Excel Application object Dim objExcel 'As Excel.Application Dim objExcel2 'As Excel.Workbooks Dim objXLWorkbook 'As Excel.Workbook On Error Resume Next Set objExcel = GetObject(,"Excel.Application") If Not (IsNull(objExcel) Or IsEmpty(objExcel)) Then WScript.Echo ("Excel application instance Exists..") 'Set objXLWorkbook = objExcel.ActiveWorkbook 'You can set this property to True if you want to close a modified workbook 'without either saving it or being prompted to save it. objExcel.ActiveWorkbook.Saved = True objExcel.ActiveWorkbook.Close objExcel.Application.Quit 'objExcel.Worksbooks.Close 'objExcel.Quit Set objExcel = Nothing Set objExcel2 = GetObject(,"Excel.Application") If Not (IsNull(objExcel2) Or IsEmpty(objExcel2)) Then Set objExcel2 = Nothing WScript.Echo ("FAIL. Excel application is not closed properly.") Else WScript.Echo ("PASS. Successfully closed Excel application.") End If WScript.Echo ("End - Closing excel application instance.") else WScript.Echo ("Excel application instance does not exist!....") End If End Sub

Friday, August 22, 2008

VBA - Extract Pictures from Excel

Last month, I have written Excel Automation Using VBScript. Today this post is to extract Pictures from Excel. Generally We can not use Export method for pictures. But we can use for Excel charts. I tried to extract our SVG chart image by macro and I succeed on it. I got help from Export pictures from Excel Below I've given the VBA Macro code.

VBA Macro - To extract Picture from Excel

Sub GetFirstPicture() Dim sCurrPath As String Dim aWorkSheet As Excel.Worksheet Dim aShape As Excel.Shape Dim aShapeChart As Excel.Shape Dim aPicture As Variant Dim aChart As Excel.Chart Dim sCurrentSheet As String Dim aImage As Variant Dim iIndex As Integer Dim iShapeCount As Integer Dim MyChart As String, MyPicture As String Dim PicWidth As Long, PicHeight As Long Dim sChartJpg As String Dim sChartGif As String Dim sChartBmp As String 'On Error GoTo ErrHandler On Error Resume Next Application.ScreenUpdating = False sCurrPath = "D:\VB\MyTrials\ChartExpFromXL" sChartJpg = "D:\VB\MyTrials\ChartExpFromXL.jpg" sChartGif = "D:\VB\MyTrials\ChartExpFromXL.gif" sChartBmp = "D:\VB\MyTrials\ChartExpFromXL.bmp" Set aWorkSheet = ActiveWorkbook.ActiveSheet sCurrentSheet = aWorkSheet.Name 'MsgBox CStr(msoTrue) + " value for MsoTrue" ' MsoTrue equals to -1 MsgBox "Shapes count " + CStr(aWorkSheet.Shapes.Count) For iIndex = 1 To aWorkSheet.Shapes.Count Set aShape = aWorkSheet.Shapes(iIndex) MyPicture = aShape.Name MsgBox aShape.Name + " Name, " + Str(aShape.Type) 'Picture 1 Name, 13 If Left(aShape.Name, 7) = "Picture" Then With aShape PicHeight = .Height PicWidth = .Width End With 'Set aChart = aWorkSheet.ChartObjects(1) Set aChart = ActiveWorkbook.Charts.Add ActiveWorkbook.ActiveChart.Location Where:=xlLocationAsObject, Name:=sCurrentSheet iShapeCount = aWorkSheet.Shapes.Count Set aShapeChart = aWorkSheet.Shapes(iShapeCount) MyChart = aShapeChart.Name '"Chart " & Str(aWorkSheet.Shapes.Count) aShapeChart.Width = PicWidth aShapeChart.Height = PicHeight With aWorkSheet aShape.Copy With ActiveChart 'aChart .ChartArea.Select .Paste End With .ChartObjects(1).Chart.Export Filename:=sChartJpg, FilterName:="jpg", Interactive:=True .ChartObjects(1).Chart.Export Filename:=sChartGif .ChartObjects(1).Chart.Export Filename:=sCurrPath & ".png" 'Not working .ChartObjects(1).Chart.Export Filename:=sChartBmp, FilterName:="bmp" aShapeChart.Cut End With Application.ScreenUpdating = True MsgBox "Completed." Exit Sub End If Next MsgBox "Completed." Exit Sub ErrHandler: MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description & " " & Err.Source Err.Clear ' Clear the error. End Sub

Saturday, July 19, 2008

Excel Automation Using VBScript

Using VBScript, we can automate most of the Excel verification activities. In one project we can export reports to Excel. I have to verify the cell value, font color and Background color. It is difficult task to verify each cell property by any GUI testing tool. All tools are used to identify Excel Grid (Workbook) as Custom Object. I am using VBScript to read the excel contents. Another advantage, you can use the VBScript against different versions of Excel such as 2002, 2003 and 2007. But you need to change the code for Excel 2003 and 2007, if you have done by using GUI objects.

Below I put one Visual Basic script code. It reads the given excel file and put the details of each cell into a log file. Copy all contents from below textbox and save it as MyExcel.vbs and try to run this VBS file. You can run this script by using any GUI Testing tool. Command line call should be cscript MyExcel.vbs sExcelFile iStartRow iStartCol iEndRow iEndCol iSheetIndex

To Know more about this VBA Help, download help from this link Microsoft Office 2003 Editions: Excel VBA Language Reference

If you are unable to run any VBScript, See my earlier post Unable to run VBS or CScript in Windows XP .

VB Script to Read Excel Contents



' USAGE: MyExcel.vbs "D:\VB\Complex.xls" iStartRow iStartCol iEndRow iEndCol iSheetIndex
'cscript MyExcel.vbs "D:\VB\Complex.xls" 1 1 30 12 2

'******** Variables Declaration
' Files section
'XLS File name
gsFile="D:\VB\Complex.xls" 'File with macros
gsLogFile="D:\VB\Results_vbs.log"

Dim gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex
Dim gsResultsFile 'Text file name
gsDirSeparator = "\" 'Directory separator character


If WScript.Arguments.Count = 6 Then
gsExcelFile = WScript.Arguments.Item(0)
giStartRow = CInt (WScript.Arguments.Item(1))
giStartCol = CInt (WScript.Arguments.Item(2))
giEndRow = CInt (WScript.Arguments.Item (3))
giEndCol = CInt (WScript.Arguments.Item (4))
giSheetIndex = CInt (WScript.Arguments.Item (5))
'To Read the Excel file
'ReadExcel gsFile, 1, 1, 30, 12, 2
'WScript.Echo "ReadExcel " , gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex
ReadExcel gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex

Else
'WScript.Echo "Usage: MyExcel.vbs sExcelFile iStartRow iStartCol iEndRow iEndCol iSheetIndex"
'WScript.Quit
ReadExcel gsFile, 1, 1, 30, 12, 2
End If

'ReadExcel gsFile, 1, 1, 30, 12, 2

'---------------------------------
' Method : ReadExcel
' Author : T. Palani Selvam
' Purpose : Reading Excel contents.
' Parameters: - Nil
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil

' Revision History:
'
' [No] da-mon-year Name: Action:
' [ 1] 07-Nov-2007 Palani Created first version
'---------------------------------
Sub ReadExcel(sExcelFile, iStartRow, iStartCol, iEndRow, iEndCol, iSheetIndex)

'WScript.Echo "ReadExcel " , sExcelFile, iStartRow, iStartCol, iEndRow, iEndCol, iSheetIndex
'ReadExcel(sExcelFile As Variant, iStartRow As Integer, iStartCol As Integer, iEndRow As Integer, iEndCol As Integer,iSheetIndex As Integer)

' Purpose: For Excel verification
' To Read the Excel and write into a file
' Each cell content
' Each cell - Foreground color, font name, font style, font size and Background color.


Dim sExcelPath 'As Variant 'Excel file

'********** Excel object declaration **********'
' Excel Application object
Dim objExcel 'As Excel.Application
Dim objXLWorkbooks 'As Excel.Workbooks
Dim objXLWorkbook 'As Excel.Workbook

Dim WorkSheetCount 'As Variant 'Work sheets count in a excel
Dim CurrentWorkSheet 'As Excel.Worksheet ' Current worksheet
Dim objCells 'As Excel.Range
Dim objCurrentCell 'As Variant
Dim objFont 'As Variant

' Result contents
Dim sCellValue 'As Variant
Dim sShowCellValue 'As Variant
Dim sFontName 'As Variant
Dim sFontStyle 'As Variant
Dim iFontSize 'As Variant
Dim iBackColorIndex 'As Variant
Dim iForeColorIndex 'As Variant
Dim iBackColorIndex2 'As Variant
Dim iForeColorIndex2 'As Variant
Dim sResult 'As Variant


' Row and Col integer variables
Dim iUsedRowsCount 'As Integer
Dim iUsedColsCount 'As Integer
Dim iTop, iLeft 'As Integer
Dim iRow 'As Integer 'Row item
Dim iCol 'As Integer 'Col item
Dim iCurRow 'As Integer
Dim iCurCol 'As Integer


If (sExcelFile = "") Then
sExcelPath = "D:\VB\Contacts.xls"
Else
sExcelPath = sExcelFile
End If

if (iSheetIndex = "") Then
iSheetIndex =1
End If


FileDeleteAndCreate (gsLogFile)

'XL file check
If (FileExists (sExcelPath) <> 0) Then
LogWrite ("The Excel file " & Chr(34) & sExcelPath & Chr(34) & " does not exit!")
'WScript.Echo "The Excel file, " & Chr(34) & sExcelPath & Chr(34) & " does not exit!"
'WScript.Quit
Else
LogWrite ("The XL file " & sExcelPath & " exists.")
End If

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open sExcelPath, False, True
'WScript.Echo "Reading data from " & sExcelPath
' objExcel.ExecuteExcel4Macro

'On Error GoTo ErrorHandler1
On Error Resume Next


WorkSheetCount = objExcel.Worksheets.Count
'WScript.Echo "We have " & WorkSheetCount & " worksheets."
'Set objXLWorkbook = objExcel.Workbooks(1)
Set objXLWorkbook = objExcel.ActiveWorkbook
'objXLWorkbook.RunAutoMacros

Set CurrentWorkSheet = objExcel.ActiveWorkbook.Worksheets(iSheetIndex) 'iSheetIndex worksheet
'Set CurrentWorkSheet = objExcel.ActiveWorkbook.Worksheets(1) 'First worksheet
' CurrentWorkSheet = objExcel.Worksheets(1) 'First worksheet


iUsedRowsCount = iEndRow 'CurrentWorkSheet.UsedRange.Rows.Count
iUsedColsCount = iEndCol 'CurrentWorkSheet.UsedRange.Columns.Count
iTop = iStartRow 'CurrentWorkSheet.UsedRange.Row
iLeft = iStartCol 'CurrentWorkSheet.UsedRange.Column

' Cells object
CurrentWorkSheet.Cells.Activate

For iRow = iTop To iUsedRowsCount '(iUsedRowsCount - 1)
'Read All rows
For iCol = iLeft To iUsedColsCount '(iUsedColsCount - 1)
'Read all Columns

sResult = ""

Set objCurrentCell = CurrentWorkSheet.Cells(iRow, iCol)
sCellValue = objCurrentCell.Value

'If ((sCellValue = empty) Or (sCellValue = "empty")) Then
If ((sCellValue = empty)) Then
sCellValue = "empty"
Else
Set objFont = objCurrentCell.Font
sFontName = objFont.Name

sFontStyle = objFont.FontStyle
iFontSize = objFont.Size
iForeColorIndex = objFont.Color
iForeColorIndex2 = objFont.ColorIndex

If (sFontName = Empty) Then
sFontName = "empty"
End If
If (sFontStyle = Empty) Then
sFontStyle = "empty"
End If
If (iFontSize = Empty) Then
iFontSize = "-99999999"
End If
If (iForeColorIndex = Empty) Then
iForeColorIndex = "99999999"
End If
If (iForeColorIndex2 = Empty) Then
iForeColorIndex2 = "99999999"
End If
sResult = "Reading Cell {" & CStr(iRow) & "," & CStr(iCol) & "}," & sCellValue & "," & sFontName & "," & CStr(sFontStyle) & "," & CStr(iFontSize) & "," & CStr(iForeColorIndex) & "," & CStr(iForeColorIndex2)

LogWrite (sResult)

End If
Set objCurrentCell = Nothing

Next

Next

' This will prevent Excel from prompting us to save the workbook.
objExcel.ActiveWorkbook.Saved = True
Set CurrentWorkSheet = Nothing

'objExcel.Worksbooks.Close
objExcel.Quit

''Set CurrentWorkSheet = Nothing
Set objExcel = Nothing


MsgBox "Read COmpleted.", vbOKOnly, "Exec Over"
Exit Sub

ErrorHandler1:
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear ' Clear the error.

End Sub

'---------------------------------
' Method : Logwrite
' Author : T. Palani Selvam
' Purpose : Append the given message into Log file.
' Parameters: sMsg - String, Contains logging message.
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil

' Revision History:
'
' [No] da-mon-year Name: Action:
' [ 1] 07-Nov-2007 Palani Created first version
'---------------------------------
Sub LogWrite(sMsg)
Const ForAppending = 8
'FileName = "D:\VBs\Mysamples\1create.txt"

Set objFSO = CreateObject("scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (gsLogFile, ForAppending, True)

objTextFile.WriteLine date & " " & time & ": " & sMsg
objTextFile.Close

Set objTextFile = Nothing
Set objFSO = Nothing
End Sub

'---------------------------------
' Method : FileExists
' Author : T. Palani Selvam
' Purpose : Checks the given file is avialable or not.
' Parameters: - Nil
' Returns : - Returns As Boolean
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Function FileExists(strPathName)
'return 0 if a file exists else -1
Dim ObjFSO

Set ObjFSO = CreateObject("Scripting.FileSystemObject")

if ObjFSO.FileExists(strPathName) = False then
FileExists = -1
else
FileExists = 0
end If

Set ObjFSO = Nothing
End Function

'---------------------------------
' Method : FileDeleteAndCreate
' Author : T. Palani Selvam
' Purpose : To delete the file if exists..
' Parameters: - Nil
' Returns : - Returns As Boolean
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Function FileDeleteAndCreate(strFileName)
' delete
Set objFSO = CreateObject("Scripting.FileSystemObject")

On Error Resume Next
Set objTextFile = objFSO.GetFile(strFileName)
objTextFile.Delete

Set objTextFile = objFSO.CreateTextFile(strFileName)

objTextFile.Close
Set objTextFile = Nothing
Set objFSO = Nothing

End Function

'---------------------------------
' Method : Initialize
' Author : T. Palani Selvam
' Purpose : Initial actions & arrangements will be completed.
' Parameters: - Nil
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Sub Initialize()
'CHECKING INPUT FILES ARE AVAILABLE OR NOT
gsLogFile = App.Path & "\Results.log"
End Sub

Wednesday, April 30, 2008

Accessing Excel - SilkTest

Few tools are providing built-in functions to read and write the data from Excel. Testers are comfortable with Excel than text file formats.

Silktest does not have any built-in functions to access data from Excel. But you can retrieve the data from Excel by treating Excel as Database. By using below code snippet, you can access the Excel data without pre-defined DSN. For this code snipper, You need to provide Excel filename with full path and worksheet name.

Silktest Excel - Code:

[+] public void ProcessExcelData(STRING sExcelFile, String sExcelSheet) [ ] // Purpose: Drives test suite based on excel sheet(testcase) information. [ ] // Executes for given worksheet. [ ] //SQL declaration [ ] HANDLE hDB [ ] HANDLE hSQL [ ] List of STRING glsData //To get testdata [ ] [ ] Print ("Test data:{sExcelFile} & Worksheet: {sExcelSheet} ") [ ] [-] do [ ] hDB = DB_Connect ("DRIVER=Microsoft Excel Driver (*.xls);DRIVERID=790;FIRSTROWHASNAMES=1;READONLY=FALSE;DBQ={sExcelFile}") [ ] [ ] //execute a SQL statement [ ] hSQL = DB_ExecuteSQL (hDB, "SELECT * from [{sExcelSheet}$]") [ ] //while there are still rows to retrieve [-] while DB_FetchNext (hSQL, glsData) [ ] GetListData (glsData) //Get all data without null [ ] [ ] [ ] //clean up the query [ ] DB_FinishSql (hSQL) [ ] [ ] //disconnect from the database [ ] DB_Disconnect (hDB) [ ] [-] except [ ] ExceptLog() [ ] Print ("Excelsheet {sExcelFile} couldn't be accessed by SilkTest.")

Wednesday, April 2, 2008

VisualTest - Using Excel Application

Our Automation suite results were in text files. I wanted to create the excel file as results file. You can get to know more about Results Reporting. I used Excel VBA for this. It has simplified my task to prepare the compiled results for entire execution.

Similarly I will write, how to do the same thing by using VB script later....

Code: To check Excel availability in the system



'--------------------------------------
' Method : IsExcelAvailable
' Author : T.Palani Selvam
' Purpose : Checks whether excel application is available or not.
' Parameters: - Nil
' Returns : Returns integer, whether true or false.
' Caller :
' Calls :
'--------------------------------
Function IsExcelAvailable() As Integer
Dim objExcelApp As Variant

ON LOCAL ERROR GOTO Errhandler

IsExcelAvailable = False
objExcelApp = OleCreateObject("Excel.Application")
Sleep 0.5
OleReleaseObject(objExcelApp)
IsExcelAvailable = True
Exit Function

ErrHandler:
'LogWrite("[Failed At] " + ERF(0)+ "("+ str(ERL) +") : "+ ERROR$ + " .Error Number: " + str(Err),1) 'Actual location.
'Logwrite("[Trapped At] "+ ERF(1)+ "("+ str(ERL(1))+ ")",1) 'Trapped location.
Logwrite("Excel Application is not available.", 2)
End Function


Code: To Read Excel data


'---------------------------------------
' Method : ReadExcelCells
' Author : T.Palani Selvam
' Purpose : Read the content from given Excel file
' and checks result automatically, while completing a test case.
' Parameters: - Nil -
' Returns : - Nil -
' Caller :
' Calls :
'
'--------------------------------------
Function ReadExcelCells(sExcelFile as String, sWorkBook as String,sWorkSheet as String,sArrFields() As String) As Integer
DIM objExcelApp As Variant,objExcel As Variant, objCurrentCell As Variant
DIM objWorkBook As Variant,objWorkSheet As Variant

Dim iRows As Integer, iCols As Integer
Dim iRowStatus As Integer, iColStatus As Integer
Dim iRowIndex As integer, iColIndex As integer, iIndex As Integer
Dim sCellValue As String, sValue as String

ReadExcelCells = False

objExcel = OleGetObject (sExcelFile)
objExcelApp = OleDispatch (objExcel,"Application")
'objExcelApp = OleCreateObject ("Excel.Application")
objWorkBook = OleDispatch (objExcelApp,"Workbooks", sWorkBook)
'objWorkBook = OleDispatch (objExcelApp,"Workbooks")
'OleDispatch(objWorkBook,"Add",sWorkBook)
objWorkSheet= OleDispatch (objWorkBook,"Sheets", sWorkSheet)

iIndex = 1
Do While Not (iRowStatus)
objCurrentCell= OleDispatch (objWorkSheet, "Cells", iIndex, 1)
sValue = OleGetProperty (objCurrentCell, "Value")
If (Len(Trim(sValue)) = 0 ) Then
iRowStatus = True
End IF
iIndex = iIndex + 1
Loop
iRows = iIndex - 2 'Rows Count
print "No of rows.." + str(iRows)

iIndex = 1
Do While Not (iColStatus)
objCurrentCell= OleDispatch (objWorkSheet, "Cells", 1, iIndex)
sValue = OleGetProperty (objCurrentCell, "Value")
If (Len(Trim(sValue)) = 0 ) Then
iColStatus = True
End IF
iIndex = iIndex + 1
Loop
iCols = iIndex - 2 'Rows Count
print "No of Columns.." + str(iCols)

ReDim sArrFields(iCols - 1,1) As String
For iIndex=1 To iCols
objCurrentCell= OleDispatch (objWorkSheet, "Cells", 1, iIndex)
sValue = OleGetProperty (objCurrentCell, "Value")
sArrFields(iIndex-1, 0) = sValue
Next iIndex


For iRowIndex = 2 To iRows
For iColIndex = 1 To iCols
objCurrentCell= OleDispatch (objWorkSheet, "Cells", iRowIndex, iColIndex)
sValue = OleGetProperty (objCurrentCell, "Value")
sArrFields(iColIndex-1, 1) = sValue
Next iColIndex
For iIndex = LBOUND(sArrFields,1) TO UBOUND(sArrFields,1)
Print "Field (Name,Value): " + sArrFields(iIndex, 0),sArrFields(iIndex, 1)
'Print "Field Value: " + sArrFields(iIndex, 1)
Next iIndex
Next iRowIndex

OleReleaseObject (objWorkSheet)
OleReleaseObject (objWorkBook)
OleReleaseObject (objExcelApp)
OleReleaseObject (objExcel)

ReadExcelCells = True
End Function


Code: To set Test Results by different colors


'-------------------------------------------------------------------------
' Method : setResultXLDetails
' Author : T.Palani Selvam
' Purpose : Set the standard format for the given Cell Object.
' Parameters: sDetails - String, contains information to be written into Excel cell object
' lRow - Long, contains row number
' lCol - long, contains Column number
' iFontType As Integer
' iFontColor As Integer
' Returns : -Nil
' Caller :
' Calls :
'-------------------------------------------------------------------------
'Default values will be given iFontType =0, iFontColor =0
Sub setResultXLDetails(sDetails As String, lRow As Long, lCol As Long,iFontType As Integer, iFontColor As Integer)
Dim objCell As Variant, objFont As Variant

If Not IsNull(gObjWorkBook) Then
objCell = OleDispatch(gObjWorkSheet,"Cells",lRow,lCol)
objFont = OleDispatch(objCell, "Font")
Select Case iFontType
Case 1
OleSetProperty(objFont,"Bold",True)
Case 2
OleSetProperty(objFont,"Italic",True)
Case 3
OleSetProperty(objFont,"Bold",True)
OleSetProperty(objFont,"Italic",True)
Case Else
End Select

Select Case iFontColor
Case Is < 1
Case Is < 26
OleSetProperty(objFont,"ColorIndex",iFontColor)
Case Else
End Select

OleSetProperty(objCell,"Value", sDetails)
OleReleaseObject(objFont)
OleReleaseObject(objCell)
End IF
End Sub


Code: To set value into given cell


'-------------------------------------------------------------------------
' Method : setResultDetails
' Author : T.Palani Selvam
' Purpose : Set the standard format for the given Cell Object.
' Parameters: sDetails - String, contains information to be written into Excel cell object
' lRow - Long, contains row number
' lCol - long, contains Column number
' Returns : -Nil
' Caller :
' Calls :
'-------------------------------------------------------------------------
Sub setResultDetails(sDetails As String, lRow As Long, lCol As Long)
Dim objCell As Variant
If Not IsNull(gObjWorkBook) Then
objCell = OleDispatch(gObjWorkSheet,"Cells",lRow,lCol)
OleSetProperty(objCell,"Value", sDetails)
OleReleaseObject(objCell)
End IF
End Sub