Createobject excel application что это

Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше

Примечание: Функция, метод, объект или свойство, описанные в данном разделе, отключаются, если служба обработки выражений Microsoft Jet выполняется в режиме песочницы, который не позволяет рассчитывать потенциально небезопасные выражения. Для получения дополнительных сведений выполните в справке поиск по словам «режим песочницы».

Создает и возвращает ссылку на объект ActiveX.

Синтаксис

CreateObject
(

класс
[, имя_сервера] )

Функция CreateObject имеет следующие аргументы:

Аргумент

Описание


класс

Обязательный аргумент. Variant (String). Имя приложения и класс создаваемого объекта.


имя_сервера

Необязательный аргумент. Variant (String). Имя сетевого сервера, где будет создан объект. Если имя_сервера является пустой строкой («»), используется локальный компьютер.

Аргумент классаргумент использует синтаксис имя_приложения.тип_объекта и содержит следующие части:

Элемент

Описание


имя_приложения

Обязательный аргумент. Variant (String). Имя приложения, предоставляющего объект.


тип_объекта

Обязательный аргумент. Variant (String). Тип (класс) объекта, который требуется создать.

Замечания

В каждом приложении, поддерживающем автоматизацию, имеется хотя бы один тип объекта. Например, в приложении для обработки текстов могут быть объекты Application, Document и Toolbar.

Чтобы создать ActiveX, назначьте объекту CreateObject объекту, объектная переменная:

Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.

' Declare an object variable to hold the object 
' reference. Dim as Object causes late binding.
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")

В этом примере мы автоматиз будем автоматизировать объект электронной таблицы Excel из базы данных Access. Этот код запускает приложение, созда которое создает объект, в данном случае таблицу Microsoft Excel. На созданный объект можно ссылаться в коде с помощью определенной вами объектной переменной. В следующем примере доступ к свойствам и методам нового объекта осуществлялся с помощью объектной переменной, ExcelSheet и других объектов Excel, включая объект Application и коллекцию Cells.

' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
' Save the sheet to C:test.xls directory.
ExcelSheet.SaveAs "C:TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
Set ExcelSheet = Nothing

При объявлении объектной переменной с помощью предложения As Object создается переменная, которая может содержать ссылку на любой тип объекта. Однако обращение к объекту через эту переменную выполняется с поздним связыванием, то есть привязка создается при выполнении программы. Чтобы создать объектную переменную с ранним связыванием, то есть со связыванием при компиляции программы, объявите объектную переменную с определенным идентификатором класса. Например, объявите и создайте следующие ссылки Excel:

Dim xlApp As Excel.Application 
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

С помощью ссылки на ранняя переменная можно улучшить производительность, но она может содержать только ссылку на класс, заданную в объявление.

Можно передать объект, возвращаемый функцией CreateObject, функции, которая использует объект в качестве аргумента. Например, в следующем коде создается и передается ссылка на объект Excel.Application:

Call MySub (CreateObject(«Excel.Application»))

Вы можете создать объект на удаленном компьютере, подключенном к сети, указав его имя в аргументе имя_сервера функции CreateObject. Это имя совпадает с именем компьютера в имени общего ресурса: для имени «\MyServerPublic» имя_сервера будет «MyServer».

Примечание:  Дополнительные сведения о том, как сделать приложение видимым на удаленном сетевом компьютере, см. в документации COM (Microsoft Developer Network). Возможно, понадобится добавить раздел реестра для приложения.

Следующий код возвращает номер версии экземпляра приложения Excel, запущенного на удаленном компьютере с именем MyServer:

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application", "MyServer")
Debug.Print xlApp.Version

Если удаленный сервер не существует или недоступен, возникает ошибка во время выполнения.

Примечание:  Используйте функцию CreateObject, если текущий экземпляр объекта отсутствует. Если экземпляр объекта уже запущен, запускается новый экземпляр и создается объект указанного типа. Чтобы использовать текущий экземпляр или запустить приложение и загрузить файл, следует воспользоваться функцией GetObject.

Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject.

Пример

В данном примере функция CreateObject используется для задания ссылки (

xlApp

) в Excel. Ссылка используется для доступа к свойству «Видимый» в Excel, а затем используется метод выхода Excel, чтобы закрыть его. Наконец, выпустится сама ссылка.

Dim xlApp As Object    ' Declare variable to hold the reference.
Set xlApp = CreateObject("excel.application")
' You may have to set Visible property to True
' if you want to see the application.
xlApp.Visible = True
' Use xlApp to access Microsoft Excel's
' other objects.
xlApp.Quit ' When you finish, use the Quit method to close
Set xlApp = Nothing ' the application, then release the reference.

Нужна дополнительная помощь?

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

CreateObject function (Visual Basic for Applications)

vblr6.chm1010851

vblr6.chm1010851

office

d887c3d3-5c60-09a1-6856-49f7c4cc05ba

12/11/2018

high

Creates and returns a reference to an ActiveX object.

Syntax

CreateObject(class, [ servername ])

The CreateObject function syntax has these parts:

Part Description
class Required; Variant (String). The application name and class of the object to create.
servername Optional; Variant (String). The name of the network server where the object will be created. If servername is an empty string («»), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part Description
appname Required; Variant (String). The name of the application providing the object.
objecttype Required; Variant (String). The type or class of object to create.

Remarks

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable.

' Declare an object variable to hold the object 
' reference. Dim as Object causes late binding. 
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. After an object is created, you reference it in code by using the object variable you defined. In the following example, you access properties and methods of the new object by using the object variable, ExcelSheet, and other Microsoft Excel objects, including the Application object and the Cells collection.

' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
' Save the sheet to C:test.xls directory.
ExcelSheet.SaveAs "C:TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
Set ExcelSheet = Nothing

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

Dim xlApp As Excel.Application 
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

Call MySub (CreateObject("Excel.Application"))

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name; for a share named «MyServerPublic,» servername is «MyServer.»

The following code returns the version number of an instance of Excel running on a remote computer named MyServer:

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application", "MyServer")
Debug.Print xlApp.Version

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

[!NOTE]
Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

Dim xlApp As Object    ' Declare variable to hold the reference.
    
Set xlApp = CreateObject("excel.application")
    ' You may have to set Visible property to True
    ' if you want to see the application.
xlApp.Visible = True
    ' Use xlApp to access Microsoft Excel's 
    ' other objects.
    ' Closes the application using the Quit method
xlApp.Quit    

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

Содержание

  1. CreateObject function
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. CreateObject Function
  8. Example
  9. Функция CreateObject
  10. Синтаксис
  11. Примечания
  12. Пример
  13. См. также
  14. Поддержка и обратная связь
  15. VBA CreateObject (Create Object)
  16. Create Object
  17. VBA Coding Made Easy
  18. VBA Code Examples Add-in

CreateObject function

Creates and returns a reference to an ActiveX object.

Syntax

CreateObject(class, [ servername ])

The CreateObject function syntax has these parts:

Part Description
class Required; Variant (String). The application name and class of the object to create.
servername Optional; Variant (String). The name of the network server where the object will be created. If servername is an empty string («»), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part Description
appname Required; Variant (String). The name of the application providing the object.
objecttype Required; Variant (String). The type or class of object to create.

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable.

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. After an object is created, you reference it in code by using the object variable you defined. In the following example, you access properties and methods of the new object by using the object variable, ExcelSheet , and other Microsoft Excel objects, including the Application object and the Cells collection.

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name; for a share named «MyServerPublic,» servername is «MyServer.»

[!NOTE] > Refer to COM documentation (see _Microsoft Developer Network_) for additional information about making an application visible on a remote networked computer. You may have to add a registry key for your application.—>

The following code returns the version number of an instance of Excel running on a remote computer named MyServer :

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

This example uses the CreateObject function to set a reference ( xlApp ) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

CreateObject Function

Note: The function, method, object, or property described in this topic is disabled if the Microsoft Jet Expression Service is running in sandbox mode, which prevents the evaluation of potentially unsafe expressions. For more information on sandbox mode, search for «sandbox mode» in Help.

Creates and returns a reference to an ActiveX object.

The CreateObject function syntax has these arguments:

Required. Variant ( String). The application name and class of the object to create.

Optional. Variant ( String). The name of the network server where the object will be created. If servername is an empty string («»), the local computer is used.

The classargument uses the syntax appname . objecttype and has these parts:

Required. Variant ( String). The name of the application providing the object.

Required. Variant ( String). The type or class of object to create.

Every application that supports automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable:

Note: Examples that follow demonstrate the use of this function in a Visual Basic for Applications (VBA) module. For more information about working with VBA, select Developer Reference in the drop-down list next to Search and enter one or more terms in the search box.

In this example, we will be automating an Excel spreadsheet object from within an Access database. This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. Once an object is created, you reference it in code using the object variable you defined. In the following example, you access properties and methods of the new object using the object variable, ExcelSheet , and other Excel objects, including the Application object and the Cells collection.

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Excel references:

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

Call MySub (CreateObject(«Excel.Application»))

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name: for a share named «\MyServerPublic,» servername is «MyServer.»

Note: Refer to COM documentation (see Microsoft Developer Network) for additional information on making an application visible on a remote networked computer. You may have to add a registry key for your application.

The following code returns the version number of an instance of Excel running on a remote computer named MyServer :

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

Note: Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

This example uses the CreateObject function to set a reference (

) to Excel. It uses the reference to access the Visible property of Excel, and then uses the Excel Quit method to close it. Finally, the reference itself is released.

Источник

Функция CreateObject

Создает и возвращает ссылку на объект ActiveX.

Синтаксис

CreateObject(класс, [ имя_сервера ])

Синтаксис функции CreateObject состоит из следующих частей:

Часть Описание
класс Обязательный элемент, Variant (String). Имя приложения и класс создаваемого объекта.
имя_сервера Необязательный элемент, Variant (String). Имя сетевого сервера, где будет создан объект. Если имя_сервера является пустой строкой («»), используется локальный компьютер.

Аргументкласса использует синтаксис appname. objecttype и состоит из следующих частей:

Part Описание
имя_приложения Обязательный элемент; Variant (String). Имя приложения, предоставляющего объект.
тип_объекта Обязательный элемент, Variant (String). Тип или класс создаваемого объекта.

Примечания

Каждое приложение, поддерживающее автоматизацию, предоставляет как минимум один тип объекта. Например, в приложении для обработки текстов могут быть объекты Application, Document и Toolbar.

Чтобы создать объект ActiveX, назначьте объект, возвращаемый функцией CreateObject, переменной объекта.

Этот код запускает приложение, в котором создается объект, в данном случае электронная таблица Microsoft Excel. После создания объекта на него можно ссылаться в коде, используя переменную объекта. В приведенном ниже примере доступ к свойствам и методам нового объекта осуществлялся с помощью объектной переменной ExcelSheet и других объектов Microsoft Excel, включая объект Application и коллекцию Cells .

При объявлении объектной переменной с помощью предложения As Object создается переменная, которая может содержать ссылку на любой тип объекта. Однако обращение к объекту через эту переменную выполняется с поздним связыванием, то есть привязка создается при выполнении программы. Чтобы создать объектную переменную с ранним связыванием, то есть со связыванием при компиляции программы, объявите объектную переменную с определенным идентификатором класса. Например, можно объявить и создать следующие ссылки Microsoft Excel:

Ссылка с ранней привязкой может обеспечить большее быстродействие, но может содержать ссылку только на класс, указанный в объявлении.

Можно передать объект, возвращаемый функцией CreateObject, функции, которая использует объект в качестве аргумента. Например, в следующем коде создается и передается ссылка на объект Excel.Application:

Вы можете создать объект на удаленном компьютере, подключенном к сети, указав его имя в аргументе имя_сервера функции CreateObject. Это имя совпадает с частью имени компьютера в имени общей папки; для общей папки с именем «MyServerPublic» имя сервера имеет значение «MyServer».

[!NOTE] > Refer to COM documentation (see _Microsoft Developer Network_) for additional information about making an application visible on a remote networked computer. You may have to add a registry key for your application.—>

Следующий код возвращает номер версии экземпляра приложения Excel, запущенного на удаленном компьютере с именем MyServer :

Если удаленный сервер не существует или недоступен, возникает ошибка во время выполнения.

Используйте функцию CreateObject, если текущий экземпляр объекта отсутствует. Если экземпляр объекта уже запущен, запускается новый экземпляр и создается объект указанного типа. Для использования текущего экземпляра или запуска приложения с одновременной загрузкой файла используйте функцию GetObject.

Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject.

Пример

В этом примере функция CreateObject используется для создания ссылки ( xlApp ) на Microsoft Excel. Эта ссылка используется для доступа к свойству Visible Microsoft Excel, а затем используется метод Quit Microsoft Excel, чтобы закрыть это приложение. В конце ссылка освобождается.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA CreateObject (Create Object)

This article will show you how to use the Create Object method in VBA.

Create Object

We can use the Create Object method to create an Object in a Microsoft Office application. For example, if we are writing VBA code in Excel, and wish to open a copy of Word, we can use the Create Object method to create a new instance of Word.

Similarly, we can create a new instance of PowerPoint or Access.

We can also use Create Object to create objects other than the Application Object. We can use it to create an Excel Sheet for example.

However, this actually creates a new instance of Excel – it does not create the sheet in the instance that is already open. For that reason, we have to set Application of the new sheet (ie: the new instance of Excel) to Visible in order to see the object.

In all of the examples above, we are using Late Binding – hence we declare the variables as Objects. We can also use Early Binding by setting a reference to Word or PowerPoint in our VBA Project and then writing the Sub Procedure as shown below. To understand more about Late and Early binding, click here.

Firstly for Early Binding, within the VBE, we set a reference to Microsoft Word.

In the Menu bar, select Tools > References and scroll down to find the reference to the Microsoft Word 16.0 Object Library.

Make sure the reference is checked, and then click OK.

NOTE: the version might not be 16.0, it all depends on what version of Microsoft Office you are running on your PC!

Now, we declare the Object using Early Binding – this means that, instead of declaring the wdApp as an Object, we declare it as a Word.Application. The rest of the code is the same as when we used Late Binding above.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

It is used to Perform Operations on Excel Application.

Excel Application

Excel File / Excel Workbook

Excel Sheet / Excel Worksheet

Create Excel Application Object

Syntax:

Set variable = CreateObject(“Class value”)

example

Set objExcel = CreateObject(“Excel.Application”)

VBScript Excel Scripting Examples:

1) Create an Excel file

Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the Operation during execution
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing

2) Check the existence of January file, If not exists then create the file.

Dim objFso, objExcel
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(“C:UsersG C REDDYDesktopJanuary.xlsx”) Then
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
End If
objExcel.Quit
Set objExcel = Nothing

3) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.

Dim objFso, objExcel, FilePath
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

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

objExcel.Quit
Set objExcel = Nothing

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 Excel files/Workbooks

Set variable = ExcelApplicationObject.Workbooks.Add/Open(“File Path”)

3) Excel Worksheet Object
It is used to work with Excel Sheets/Worksheets

Set variable = ExcelWorkbookObject.Worksheets(Sheet Id Or “Sheet Name”)

Excel Application Object is always only one

We can create one or more Excel Workbook objects

We can create one or more Excel Worksheet objects for every workbook object

Difference between FileSystemObject model and Excel object model in case of Sub Objects.

> In FileSystemObject model creating Text stream object (sub object) is mandatory to perform Text(Read, write etc…) related operations

> In Excel object model creating sub objects is optional, but if you want work with multiple files and multiple sheets then sub objects are required.

4) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.(Using Sub and Sub-sub objects)

Dim objFso, objExcel, FilePath, objWorkbook, objWorksheet
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

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

5) Read Test data from an Excel file and perform Data driven testing for Login Functionality

Dim objExcel, objWorkbook, objWorksheet, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersG C REDDYDesktopJanuary.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 for Row, A for Column
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2)’i for Row, 2 for Column
Wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
Next
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing

Follow me on social media:

Понравилась статья? Поделить с друзьями:
  • Created excel drop down list
  • Create your own forms in word
  • Create your find a word
  • Create xml for excel
  • Create worksheets in excel