Vbs open excel file

Use VBScript to create, open, and edit excel files. ( Excel needs to be installed on your computer ).


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

‘Microsoft Excel Automation Basics
‘:: Create and edit an Excel File.
‘———————————
‘create the excel object
Set objExcel = CreateObject(«Excel.Application»)
‘view the excel program and file, set to false to hide the whole process
objExcel.Visible = True
‘add a new workbook
Set objWorkbook = objExcel.Workbooks.Add
‘set a cell value at row 3 column 5
objExcel.Cells(3,5).Value = «new value»
‘change a cell value
objExcel.Cells(3,5).Value = «something different»
‘delete a cell value
objExcel.Cells(3,5).Value = «»
‘get a cell value and set it to a variable
r3c5 = objExcel.Cells(3,5).Value
‘save the new excel file (make sure to change the location) ‘xls for 2003 or earlier
objWorkbook.SaveAs «C:UsersUserNameDesktopvbsTest.xlsx»
‘close the workbook
objWorkbook.Close
‘exit the excel program
objExcel.Quit
‘release objects
Set objExcel = Nothing
Set objWorkbook = Nothing


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

‘Microsoft Excel Automation Basics
‘:: Open and edit an Excel File.
‘———————————
‘create the excel object
Set objExcel = CreateObject(«Excel.Application»)
‘view the excel program and file, set to false to hide the whole process
objExcel.Visible = True
‘open an excel file (make sure to change the location) .xls for 2003 or earlier
Set objWorkbook = objExcel.Workbooks.Open(«C:UsersUserNameDesktopvbsTest.xlsx»)
‘set a cell value at row 3 column 5
objExcel.Cells(3,5).Value = «new value»
‘change a cell value
objExcel.Cells(3,5).Value = «something different»
‘delete a cell value
objExcel.Cells(3,5).Value = «»
‘get a cell value and set it to a variable
r3c5 = objExcel.Cells(3,5).Value
‘save the existing excel file. use SaveAs to save it as something else
objWorkbook.Save
‘close the workbook
objWorkbook.Close
‘exit the excel program
objExcel.Quit
‘release objects
Set objExcel = Nothing
Set objWorkbook = Nothing

I have the following code, I want it to open my files which are saved as .xlsx and simply save them again with the same filename but this time as a .xls file so that they are compatible with Excel 2003

Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")

For Each f In fso.GetFolder("Y:Billing_Commonautoemail").Files
  If LCase(fso.GetExtensionName(f)) = "xlsx" Then
    Set wb = app.Workbooks.Open(f.Path)

app.DisplayAlerts = False

wb.SaveAs "*.xls*"
wb.Close SaveChanges=True
app.Close
app.Quit

  End if

Set f = Nothing
Set fso = Nothing
Next

Kara's user avatar

Kara

6,08516 gold badges51 silver badges57 bronze badges

asked Jul 4, 2013 at 7:50

Nathan Hawthorne's user avatar

1

As Bathsheba already pointed out, Set fso = Nothing and app.Quit belong at the end of the script (outside the loop). There are some more bugs, though.

  • wb.SaveAs "*.xls*"

    You can’t save a workbook to a wildcard name. If you want to save the workbook under its current name, just use wb.Save. Otherwise you’ll have to use an explicit name (you should also set the filetype then):

    wb.SaveAs "new.xlsx", 51
    

    or

    wb.SaveAs "C:pathtonew.xls", -4143
    
  • wb.Close SaveChanges=True

    VBScript doesn’t support named parameters (see here). If you want to call the Close method with the SaveChanges parameter set to True you have to do it like this:

    wb.Close True
    
  • app.Close

    The application object doesn’t have a Close method.

Not bugs, but things worth improving:

  • app.DisplayAlerts = False should go before the loop starts unless you re-enable it inside the loop as well.

  • I’d recommend adding a line app.Visible = False after you create the application object. When you have to debug your script you can simply change that value to True to show the application on your desktop. That helps a lot with finding bugs.

Fixed-up script:

Set app = CreateObject("Excel.Application")
app.Visible = False
app.DisplayAlerts = False

Set fso = CreateObject("Scripting.FileSystemObject")

For Each f In fso.GetFolder("Y:Billing_Commonautoemail").Files
  If LCase(fso.GetExtensionName(f)) = "xlsx" Then
    Set wb = app.Workbooks.Open(f.Path)

    wb.Save
    wb.Close True
  End if
Next

app.Quit
Set app = Nothing
Set fso = Nothing

Community's user avatar

answered Jul 4, 2013 at 8:42

Ansgar Wiechers's user avatar

Ansgar WiechersAnsgar Wiechers

190k23 gold badges244 silver badges319 bronze badges

5

Two serious bugs:

  • Set fso = Nothing should not be inside your loop: you’ll need fso
    for the duration of the program.

  • Also, drop app.Quit from the loop; keep Excel open until the very
    end.

Set f = Nothing is unnecessary (although benign); let the loop pick the values for you.

answered Jul 4, 2013 at 7:55

Bathsheba's user avatar

BathshebaBathsheba

231k33 gold badges359 silver badges477 bronze badges

Dim app, fso, file, fName, wb, dir 

dir = "d:path"

Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")

For Each file In fso.GetFolder(dir).Files
    If LCase(fso.GetExtensionName(file)) = "xlsx" Then  
    fName = fso.GetBaseName(file)

    Set wb = app.Workbooks.Open(file) 
    app.Application.Visible = False
    app.Application.DisplayAlerts = False
    app.ActiveWorkbook.SaveAs dir & fName & ".xls", 43
    app.ActiveWorkbook.Close 
    app.Application.DisplayAlerts = True 
    app.Application.Quit 

    End if
Next

Set fso = Nothing
Set wb = Nothing    
Set app = Nothing

wScript.Quit

answered Oct 23, 2014 at 15:50

Dimzay's user avatar

Содержание

  1. simply-coded / CreateExcelFile.vbs
  2. Open A Excel File using VBScript @ Windows Script Host
  3. Related Posts
  4. One Response
  5. Open an Excel file in exclusive mode using VBScript
  6. 2 Answers 2
  7. VBScript
  8. Table of Contents
  9. Sunday, September 5, 2010
  10. Working with Excel Object
  11. Calling an Excel sheet in VBScript
  12. 3 Answers 3

simply-coded / CreateExcelFile.vbs

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

‘Microsoft Excel Automation Basics
‘:: Create and edit an Excel File.
‘———————————
‘create the excel object
Set objExcel = CreateObject( «Excel.Application» )
‘view the excel program and file, set to false to hide the whole process
objExcel.Visible = True
‘add a new workbook
Set objWorkbook = objExcel.Workbooks.Add
‘set a cell value at row 3 column 5
objExcel.Cells( 3 , 5 ).Value = «new value»
‘change a cell value
objExcel.Cells( 3 , 5 ).Value = «something different»
‘delete a cell value
objExcel.Cells( 3 , 5 ).Value = «»
‘get a cell value and set it to a variable
r3c5 = objExcel.Cells( 3 , 5 ).Value
‘save the new excel file (make sure to change the location) ‘xls for 2003 or earlier
objWorkbook.SaveAs «C:UsersUserNameDesktopvbsTest.xlsx»
‘close the workbook
objWorkbook.Close
‘exit the excel program
objExcel.Quit
‘release objects
Set objExcel = Nothing
Set objWorkbook = Nothing

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Источник

Open A Excel File using VBScript @ Windows Script Host

Windows Script Host (WSH) is powerful. Every windows since Win95 come with default installation of WSH and two languages are supported, JScript (Microsoft’s implementation of Javascript) and VBScript.

Creating Automation Objects is easy. In VBScript, the syntax would be to use CreateObject function and in JScript it corresponds to new ActiveXObject function.

The below is a sample script in VBScript to open an excel file and bring the Excel Application to front.

[This] post talks about the variables scopes in Javascript. Here, we will turn to VBScript…

Scripting in Windows using VBScript or Javascript for WSH (Windows Scripting Host) is so convenient.…

The FileSystemObject provides a GetTempName method that returns a temporary file name. The following is the short…

The following script snippet is handy at checking whether a folder exists or not at…

Many software e.g. CCleaner has the powerful/advanced functionalities to search and clean the trash from…

The following is a batch script (save as *.bat or *.cmd) that can almost run…

The str_repeat function is a commonly used function that allows you to print/generate a string…

The WMI Service object on windows is very powerful, it allows us to list memory…

Ajax stands for Asynchronous Javascript and Xml. In the examples given in this post, we can see that XMLHTTP object…

WSH (Window Scripting Host) is a powerful and handy scripting environment. It is installed by…

One Response

Thanks, i used this code and worked. But i want my directory be a variable created by time update. How could work?

Источник

Open an Excel file in exclusive mode using VBScript

I have a simple question, but I’ve searched for this and couldn’t find any helpful topics..

I’m working on a VBScript that opens an Excel file and modify a few stuff in it.. so I’m using this code:

Now, what I want to do is to open the Excel file using a way that locks the file and prevents the user from opening it while it’s open by the script (until it’s closed).

Update:

I think the problem is somehow related to the Excel instances, I tried to do the following (while the file is open by the script):

  • When I manually open the file (while it’s open by the script) they’re both become a single instance.
  • When I open any other Excel file they’re both also become a single instance. And the original file (opened by the script) becomes visible!

Now this is weird because I’m using CreateObject(«Excel.Application») and not GetObject(, «Excel.Application»)

2 Answers 2

There is registry key HKEY_CLASSES_ROOTExcel.Sheet.8shellOpencommand on Win 7 Excel 2010 for me with default value «C:Program FilesMicrosoft OfficeOffice14EXCEL.EXE» /dde . The command line /dde switch enables DDE (Dynamic Data Exchange mechanism — an ancient Win 3.0 interprocess communication method) that forces Excel to start in a single instance. I’ve tried to remove that switch and opened workbooks, but to no avail. BTW, if you don’t have a permission to edit the registry, or you intend to distribute your script to someone who doesn’t, that is not a way. Also have tried this answer, but it doesn’t work for Win 7 Office 2010.

I’ve tested test.xlsm file with DDE enabled. When user opens a file, actually it is just reopened in existing instance that make it visible. If any changes has been already made by the script, then Excel alerts:

Anyway write-access is given for the user. After that when the script saves the file, another alert appears:

Some time ago I created a script that worked with Excel application, and encountered the same issue with Win 7 Excel 2010 as you are describing. I noticed that if there were several Excel application instances created with CreateObject() within script, then Excel file opened by user always used exactly the first created instance. I’ve solved the issue by creating two invisible instances of Excel application, let’s say dummy and target. In outline the algorithm for a script is as follows:

  1. Create dummy instance first, no need to add a workbook. After that the dummy instance is exposured an Excel file to be opened by user within it.
  2. Create target instance.
  3. Quit dummy instance.
  4. Open target workbook, modify and save it.
  5. Quit target instance.

Consider the below code that illustrates a possible way to implement what you need:

Trying open the file you will get desired output:

And the notification after the script ends:

Источник

VBScript

Table of Contents

Sunday, September 5, 2010

Working with Excel Object

‘Create an Microsoft Excel Object using VBScript
Set ExcelObject = CreateObject(«Excel.Application»)
ExcelObject.visible = True
ExcelObject.WorkBooks.Add ‘Adds a workbook to an excel object
ExcelObject.Sheets(1).Cells(1,1).value = «Text in the Cell» ‘Writes a text to a particular cell in the excel object

‘Open Microsoft file using VBScript
Set ExcelObject = CreateObject(«Excel.Application»)
ExcelObject.visible = True
ExcelObject.Workbooks.Open(«c:excelsheet.xls»,Default, False)
ExcelObject.Sheets(1).Cells(1,1).value = «Text to be entered»
ExcelObject.Activeworkbook.SaveAs(«d:excelsheet.xls») ‘Using Save As

‘Save the Excel Workbook
ExcelObject.Activeworkbook.save

‘Get the Number of Rows used in the Excel sheet
RowCount = ExcelObject.ActiveWorkbook.Sheets(1).UsedRange.Rows.count
msgbox «Number of rows used in the excel sheet «& RowCount

‘Get the Number of Columns used in the Excel sheet
ColumnCount = ExcelObject.ActiveWorkbook.Sheets(1).UsedRange.Columns.count
msgbox «Number of columns used in the excel sheet «&ColumnCount

‘Change the sheet name of the Excel workbook
ExcelObject.Activeworkbook.Sheets(1).Name = «NameOftheFirstSheet»
ExcelObject.Activeworkbook.Sheets(2).Name = «NameoftheSecondSheet»

‘Get the Sheet Name of the Excel workbook
FirstSheetName = ExcelObject.Activeworkbook.Sheets(1).Name
msgbox «Name of the first sheet»&FirstSheetName
SecondSheetName = ExcelObject.Activeworkbook.Sheets(2).Name
msgbox «Name of the second sheet»&SecondSheetName

‘Get the value of the Particular Cell
ValueOfTheCell = ExcelObject.Activeworkbook.Sheets(1).Range(«A1»).Value
msgbox «Value Of the Cell » & ValueOfTheCell

‘Storing and Using the data in Excel First Row as a collection in Dictionary Object
lNoofColumns = ExcelObject.Activeworkbook.Sheets(1).UsedRange.Columns.Count
Set oDic = New Collection
For lColNumber = 1 To lNoofColumns
lColValue = ExcelObject.Activeworkbook.Sheets(1).Range(GetCol(lColNumber) & «1»).Value
If (Len(lColValue) > 0) Then
oDic.Add Item:=lColNumber, Key:=CStr(LCase(lColValue))
End If
Next

Function GetCol(ColumnNumber)
FuncRange = ExcelObject.Activeworkbook.Sheets(1).Cells(1, ColumnNumber).AddressLocal(False, False)
‘Creates Range (defaults Row to 1) and returns Range in xlA1 format

FuncColLength = Len(FuncRange)
‘finds length of range reference

GetCol = Left(FuncRange, FuncColLength — 1)
‘row always «1» therefore take 1 away from string length and you are left with column ref
End Function

‘Getting the value using Column value
Msgbox «Column Number of Cell» & GetCol(oDic(«Row 1 value of the 1st Column»))

Источник

Calling an Excel sheet in VBScript

I have the following code:

It prints two random cells between row 1 and row 195 from the Excel sheet «Music». One of them — the one in column A — represents the album, and the other represents the song. The problem is that it takes quite a long time to return the results, about 20 seconds.

I was wondering whether there was a more efficient method I could use to get the results more quickly.

3 Answers 3

I think Ansgar Wiechers’ answer is probably correct that starting Excel is the slowest part of the script. You could try using ADO to connect to the Excel file as if it were a database. This would avoid starting Excel:

The one possible snag here is that VBScript is run by default using the 64-bit version of wscript.exe, and the 64-bit ACE.OLEDB is only available if you installed the 64-bit version of Office 2010 or higher. This can be worked around, though, by running the script with the 32-bit version of wscript.exe (e.g., see How do I run a VBScript in 32-bit mode on a 64-bit machine?).

If you decide to go this route and can control the input Excel file, I would recommend adding a header row to the spreadsheet and changing HDR=NO to HDR=YES in the connection string. That way, you can refer to the columns by name in the query (e.g., SELECT TOP 1 album, song . ) instead of relying on the «F1» syntax.

The most time-consuming steps in your script are most likely

  • starting Excel and
  • opening the workbook.

One thing you could do is using an already running Excel instance instead of creating a new one all the time:

The variable quitExcel indicates whether you need to close Excel at the end of your script (when you created a new instance) or not (when you used an already running instance).

You could also check if the workbook is already open:

Other than that your only options are changing the way the data is stored or buying faster hardware, AFAICS.

Cheran, I disagree with the answers here.

I just ran your script on my 5 year old laptop, and got the answer in about 2 seconds. Whether an instance of Excel was already open made no difference in run time.

(I created a test Music.xlsx spreadsheet by entering «A1» in cell A1, and «B1» in cell B1, and dragged those cells down to row 195 to get a nice set of unique sample data).

Why don’t you make Excel visible when it runs, so that you can see for yourself what is going on?

You might see, for example, that Excel takes one second to open, and the Excel Add-ins you have are taking the other fifteen seconds to initialize. It’s also possible that your machine and/or hard drive is slow and does indeed take 20 seconds to run this. Who knows.

To get some insight, please make objApp.Visible = True and rerun.

You might also comment out the final eight lines, except for the MsgBox line so that your Excel file stays open after script is done, so that you might see other clues.

Other observations: 1) Your method of opening Excel with CreateObject from a .vbs script seems to be the most reliable/accepted method of automating Excel.

Источник

  • Remove From My Forums
  • Вопрос

  • I have a script that get its search string from a text file, then searches another directory full of txt files for that string and then creates an html file with a link to each txt file it finds containing that string…

    could someone help in changing this… i still want it to search using a string it obtains from a text file… but i need it to search file names and when it finds the correct file, open it  (it needs to open excel files)

    here is the code…

    Option Explicit
    ' On Error Resume Next  - I think this is a bad idea, especially while developing an app
    
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8
    
    Dim objFSO, objFile, objHTMLFile 
    Dim strLine, strSearchFile, strPath, strLogFile
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    strSearchFile = "C:UsersFAM7DesktopFacetcoat log filesSearchString.txt" ' Set the Search File Path
    strPath = "C:UsersFAM7DesktopFacetcoat log filesNetwork Drive Folder" ' A Path to a Folder where you want to look in
    strLogFile = "C:UsersFAM7DesktopFacetcoat log filesResults.html"
    
    If objFSO.FileExists(strSearchFile) Then
      Set objFile = objFSO.OpenTextFile(strSearchFile,ForReading) ' Reading The File
      Set objHTMLFile = objFSO.OpenTextFile(strLogFile, ForWriting, true) ' Create/overwrite the Log File
      
      Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        FindInFiles strPath, strLine, objHTMLFile
      Loop
      objFile.Close
      Set objFile = Nothing
    Else
      WScript.Quit
    End If
    
    ' Clean up
    Set objFSO = Nothing
    
    Sub FindInFiles(strPath, strLine, objHTMLFile)
      Dim objFolder, FileItem, oFile
      Dim strText
      
      Set objFolder = objFSO.getFolder(strPath)
      
      For Each FileItem In objFolder.Files
        Set oFile = FileItem.OpenAsTextStream(ForReading)
        strText = oFile.ReadAll()
        If InStr(strText, strLine) Then
          objHTMLFile.WriteLine "<P><a href=""" & FileItem.Path & """>" & FileItem.Path & "</a></P>"
        End If
      Next
    End Sub

Ответы

  • OK i got it, thanks so much for all the help again!

    final working code

    Option Explicit
    
    Const ForReading = 1
    Const ForWriting = 2
    
    Dim objFSO, objFile, objExcel, objWorkBook
    Dim strLine, strSearchFile, strPath, strLogFile, strFileItemPath
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objExcel = CreateObject("Excel.Application")
    objExcel.visible = true
    
    
    strSearchFile = "C:UsersFAM7DesktopFacetcoat log filesSearchString.txt" ' Set the Search File Path
    strPath = "C:UsersFAM7DesktopFacetcoat log filesNetwork Drive Folder" ' A Path to a Folder where you want to look in
    'strLogFile = "F:DownloadsFacetcoat log files WORKResults.html"
    
    If objFSO.FileExists(strSearchFile) Then
      Set objFile = objFSO.OpenTextFile(strSearchFile,ForReading) ' Open the File to read from
    
    
    ' if you want to log this activity then include the next line
    '  Set objHTMLFile = objFSO.OpenTextFile(strLogFile, ForWriting, true) ' Create/overwrite the Log File
    
    
     Wscript.Echo "have opened " & strSearchFile
     Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine ' read file
          strFileItemPath = strPath & "" & strLine & ".xls"
    	set objWorkbook = objExcel.Workbooks.Open(strFileItemPath)
    
    
    '        if you want to log this activity then include the next line (remove comment character)
    '        objHTMLFile.WriteLine "<P><a href=""" & strFileItemPath & """>" & strFileItemPath & "</a></P>"
    
      Loop
      objFile.Close
      Set objFile = Nothing
    Else
      WScript.Quit
    End If

    • Помечено в качестве ответа

      4 ноября 2009 г. 5:09

Доброго всем дня. Очень надеюсь, что среди знатоков есть специалисты по данному языку.
Проблема у меня следующая. Требуется в vbs-скрипте прописать процедуру открытия книги и запуска макрос. С этим справиться удалось.

Код
Option Explicit
Dim app, ChangePhonesFolder, ChangePhonesFileName, inChangePhonesFullFileName, InFolderName, objExcel
Dim f, s, b, i, my_time, logs

set objExcel = CreateObject ("Excel.Application")
app="С:EXTUnZip.xlsb"

on error goto 0: TI_Avaya()

sub TI_Avaya()
   objExcel.Visible = true
        objExcel.Workbooks.Open (app)
   objExcel.run "Time_Indicators"
   objExcel.Workbooks("UnZip.xlsb").Close (true)
objExcel.Quit
end sub

Но вот как открыть документ, в режиме редактирования, если стоит соответствующий пароль. Метод vbа

Код
objExcel.Workbooks.Open (app, writerespassword:="123")

тут не подошел.

Open A Excel File using VBScript @ Windows Script Host

Windows Script Host (WSH) is powerful. Every windows since Win95 come with default installation of WSH and two languages are supported, JScript (Microsoft’s implementation of Javascript) and VBScript.

Creating Automation Objects is easy. In VBScript, the syntax would be to use CreateObject function and in JScript it corresponds to new ActiveXObject function.

The below is a sample script in VBScript to open an excel file and bring the Excel Application to front.

1
2
3
4
5
6
7
8
9
10
11
12
13
' codingforspeed.com
 
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
' directory in which this script is currently running
CurrentDirectory = fso.GetAbsolutePathName(".")
 
Dim csv: csv = fso.BuildPath(CurrentDirectory, "sample.csv")
Dim Excel
Set Excel = CreateObject("Excel.Application")
Excel.Application.Visible = True
Excel.WorkBooks.Open csv
' App Activate, bring to front
CreateObject("WScript.Shell").AppActivate Excel.Name
' codingforspeed.com

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
' directory in which this script is currently running
CurrentDirectory = fso.GetAbsolutePathName(".")

Dim csv: csv = fso.BuildPath(CurrentDirectory, "sample.csv")
Dim Excel
Set Excel = CreateObject("Excel.Application")
Excel.Application.Visible = True
Excel.WorkBooks.Open csv
' App Activate, bring to front
CreateObject("WScript.Shell").AppActivate Excel.Name

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading…

181 words
Last Post: Happy Valentine’s Day, another heart equation
Next Post: Variable Scopes in VBScript at Windows Script Host

The Permanent URL is: Open A Excel File using VBScript @ Windows Script Host (AMP Version)

(Excel Object Model in VBScript)

Excel Application operations using Excel Application Object

Excel Application Object:

It is used to perform operations on Excel Application.

Create Excel Application Object:

Set Variable = CreateObject(“Excel.Application”)
———————-
Excel Application

Excel Workbook / File

Excel Worksheet / Sheet

Excel File Operations using VBScript Examples:

1) Create an Excel file
Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the operation (Creating Excel file) during Execution.

objExcel.Workbooks.Add ‘Create New Workbook / file

objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP.xls” ‘Save the Excel workbook /file

objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing ‘To release the memory
—————————————————
2) Check the existence of QTP file, if not exist then create the file.Dim objFso, objExcel, FilePath
FilePath = “C:UsersgcreddyDesktopQTP.xls”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add ‘Create New Workbook / file
objExcel.ActiveWorkbook.SaveAs FilePath
objExcel.Quit
End If

Set objExcel = Nothing ‘To release the memory
—————————————————-
3) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Excel Application Object only)
Dim objFso, objExcel, FilePath

FilePath = “C:UsersgcreddyDesktopQTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.SaveAs FilePath
Else
objExcel.Workbooks.Open (FilePath)
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.Save
End If
objExcel.Quit

Set objExcel = Nothing

Excel Object Model in VBScript

Excel Objects

1) Excel Application Object
It is used to perform operations on Excel Application.

Set Variable = CreateObject(“Excel.Application”)
——————————–
2) Excel Workbook object
It is used to work with specified Excel file / Workbook

Set Variable = ExcelApplicationObject.Workbooks.Add / Open(“Filepath”)
——————————–
3) Excel Worksheet object
It is used to work with specified work sheet

Set Varaible = ExcelWorkbookObject.Worksheets(Sheet Id / “Sheet name”)
——————————————————-
Excel Application is always only one.

We may have one or more Workbooks.

We may have multiple sheets in every workbook.
———————————————
> Using (“Excel.Application”) class value we create Excel Application Object.

> We create Excel Workbook object using Excel Application Object.

> We create Excel Worksheet object using Excel workbook object.
————————————–
Difference between File system object model and Excel object model in case of Sub objects.

In File system object model creating Text stream object is mandatory to perform File internal operations like Read, Write, Compare, Search etc…

In Excel Object model creating sub and sub-sub objects optional, if you want to work with multiple files and multiple sheets then we can use sub and sub-sub objects.
———————————————————-
4) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Main and sub objects)

Dim objFso, objExcel, objWorkbook, objWorksheet, FilePath

FilePath = “C:UsersgcreddyDesktopQTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.SaveAs FilePath
Else
Set objWorkbook = objExcel.Workbooks.Open (FilePath)
Set objWorksheet = objworkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.Save
End If
objExcel.Quit

Set objExcel = Nothing
————————————————
5) Read data form Excel file and perform Data driven Testing for Login Functionality.
Dim objExcel, objWorkbook, objWorksheet, i, RowsCount

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)

RowsCount = objWorksheet.UsedRange.Rows.Count

For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
Next
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
————————————————
6) Read data form Excel file and perform Data driven Testing for Login Functionality. And write Test Result to the Same file 3rd column.
Dim objExcel, objWorkbook, objWorksheet, i, RowsCount

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)

RowsCount = objWorksheet.UsedRange.Rows.Count

For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click

If Window(“Flight Reservation”).Exist (12) Then
Window(“Flight Reservation”).Close
objWorksheet.Cells(i, 3) = “Login Successful – Passed”
Else
SystemUtil.CloseDescendentProcesses
objWorksheet.Cells(i, 3) = “Login Unsuccessful – Failed”
End If
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
————————————————
7) Read data form Excel file and perform Data driven Testing for Login Functionality. And write Test Result and Error messages to the same file.Dim objExcel, objWorkbook, objWorksheet, i, RowsCount

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)

RowsCount = objWorksheet.UsedRange.Rows.Count

For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click

If Window(“Flight Reservation”).Exist (12) Then
Window(“Flight Reservation”).Close
objWorksheet.Cells(i, 3) = “Login Successful – Passed”
Else
objWorksheet.Cells(i, 4) = Dialog(“Login”).Dialog(“Flight Reservations”).Static(“Agent name must be at”).GetROProperty(“text”)
SystemUtil.CloseDescendentProcesses
objWorksheet.Cells(i, 3) = “Login Unsuccessful – Failed”
End If
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
——————————————–
8) Read Button Names from Login Dialog and export to Excel file 2nd sheet.Dim objExcel, objWorkbook, objWorksheet, oButton, Buttons, i

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(2)

Set oButton = Description.Create
oButton(“Class Name”).Value = “WinButton”

Set Buttons = Dialog(“Login”).ChildObjects(oButton)
Msgbox Buttons.Count

objWorksheet.cells(1, 1) = “Button Names”

For i = 0 To Buttons.Count – 1 Step 1
objWorksheet.cells(i+2, 1) = Buttons(i).GetRoProperty(“text”)
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
—————————————————
9) Read Link names from Google Home page and export to Excel file 3rd sheet.Dim objExcel, objWorkbook, objWorksheet, oLink, Links, i

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(3)

Set oLink = Description.Create
oLink(“micclass”).Value = “Link”

Set Links = Browser(“Google”).Page(“Google”).ChildObjects(oLink)
Msgbox Links.Count

objWorksheet.cells(1, 1) = “Link Names”

For i = 0 To Links.Count – 1 Step 1
objWorksheet.cells(i+2, 1) = Links(i).GetRoProperty(“text”)
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
—————————————————
10) Read Customer names from 1 to 10 Records and export to Excel
Dim objExcel, objWorkbook, objWorksheet, Customer_Name, i

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(2)

objWorksheet.cells(1, 1) = “Customer Names”
For i = 1 To 10 Step 1
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set i
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Customer_Name = Window(“Flight Reservation”).WinEdit(“Name:”).GetROProperty(“text”)
objWorksheet.Cells(i+1, 1) = Customer_Name
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
————————————————–
11) Create an Excel File and Rename 1st sheet as “Module”, 2nd sheet as “TestCase”, and 3rd sheet as “TestStep”.
Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)

objExcel.Workbooks.Add
objExcel.Worksheets(1).Name = “Module”
objExcel.Worksheets(2).Name = “TestCase”
objExcel.Worksheets(3).Name = “TestStep”

objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP2.xlsx”
objExcel.Quit
Set objExcel = Nothing

12) Create an Excel file and Add one more sheet.Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)

objExcel.Workbooks.Add ‘Create New workbook
objexcel.Worksheets.Add ‘Create New worksheet

objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP3.xlsx”
objExcel.Quit
Set objExcel = Nothing
———————————————
Assignment:
Create an Excel file and Move 1st sheet to 3rd position.

Creation Time:

Sheet1 Sheet2 sheet3

Move 1st sheet to 3rd position

Sheet2 Sheet3 Sheet1
————————————————–
Comparison examples:

i) One to one comparison (Textual and binary)

ii) Many to many comparison
————————————————-

Follow me on social media:

Понравилась статья? Поделить с друзьями:
  • Vbnewline in excel vba
  • Vbe6ext olb could not be loaded что делать excel
  • Vbcrlf in vba excel
  • Verb doing word noun
  • Verb and noun word sort