Excel vba getobject excel application

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

GetObject function (Visual Basic for Applications)

vblr6.chm1010959

vblr6.chm1010959

office

6c313a4c-dac9-9115-95db-3fde52a5e888

12/12/2018

medium

Returns a reference to an object provided by an ActiveX component.

Syntax

GetObject([ pathname ], [ class ])

The GetObject function syntax has these named arguments:

Part Description
pathname Optional; Variant (String). The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class Optional; Variant (String). A string representing the class of the object.

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

Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:

Dim CADObject As Object
Set CADObject = GetObject("C:CADSCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated.

If pathname is a zero-length string («»), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate part of a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file that you want to activate. For information about how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

Set LayerObject = GetObject("C:CADSCHEMA.CAD!Layer3")

If you don’t specify the object’s class, automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

Dim MyObject As Object
Set MyObject = GetObject("C:DRAWINGSSAMPLE.DRW", "FIGMENT.DRAWING")

In the example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.
After an object is activated, you reference it in code by using the object variable you defined. In the preceding example, you access properties and methods of the new object by using the object variable MyObject. For example:

MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:DRAWINGSSAMPLE.DRW"

[!NOTE]
Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don’t want the object started with a file loaded, use the CreateObject 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. With a single-instance object, GetObject always returns the same instance when called with the zero-length string («») syntax, and it causes an error if the pathname argument is omitted. You can’t use GetObject to obtain a reference to a class created with Visual Basic.

Example

This example uses the GetObject function to get a reference to a specific Microsoft Excel worksheet (MyXL). It uses the worksheet’s Application property to make Microsoft Excel visible, to close it, and so on.

Using two API calls, the DetectExcel Sub procedure looks for Microsoft Excel, and if it is running, enters it in the Running Object Table.

The first call to GetObject causes an error if Microsoft Excel isn’t already running. In the example, the error causes the ExcelWasNotRunning flag to be set to True.

The second call to GetObject specifies a file to open. If Microsoft Excel isn’t already running, the second call starts it and returns a reference to the worksheet represented by the specified file, mytest.xls. The file must exist in the specified location; otherwise, the Visual Basic error Automation error is generated.

Next, the example code makes both Microsoft Excel and the window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code uses the Application object’s Quit method to close Microsoft Excel. If the application was already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.

' Declare necessary API routines:
Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName as String, _
                    ByVal lpWindowName As Long) As Long

Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd as Long,ByVal wMsg as Long, _
                    ByVal wParam as Long, _
                    ByVal lParam As Long) As Long

Sub GetExcel()
    Dim MyXL As Object    ' Variable to hold reference
                                ' to Microsoft Excel.
    Dim ExcelWasNotRunning As Boolean    ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.
    On Error Resume Next    ' Defer error trapping.
' Getobject function called without the first argument returns a 
' reference to an instance of the application. If the application isn't
' running, an error occurs.
    Set MyXL = Getobject(, "Excel.Application")
    If Err.Number <> 0 Then ExcelWasNotRunning = True
    Err.Clear    ' Clear Err object in case error occurred.

' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
    DetectExcel

' Set the object variable to reference the file you want to see.
    Set MyXL = Getobject("c:vb4MYTEST.XLS")

' Show Microsoft Excel through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyXL object reference.
    MyXL.Application.Visible = True
    MyXL.Parent.Windows(1).Visible = True
     Do manipulations of your  file here.
    ' ...
' If this copy of Microsoft Excel was not running when you
' started, close it using the Application property's Quit method.
' Note that when you try to quit Microsoft Excel, the
' title bar blinks and a message is displayed asking if you
' want to save any loaded files.
    If ExcelWasNotRunning = True Then 
        MyXL.Application.Quit
    End IF

    Set MyXL = Nothing    ' Release reference to the
                                ' application and spreadsheet.
End Sub

Sub DetectExcel()
' Procedure dectects a running Excel and registers it.
    Const WM_USER = 1024
    Dim hWnd As Long
' If Excel is running this API call returns its handle.
    hWnd = FindWindow("XLMAIN", 0)
    If hWnd = 0 Then    ' 0 means Excel not running.
        Exit Sub
    Else                
    ' Excel is running so use the SendMessage API 
    ' function to enter it in the Running Object Table.
        SendMessage hWnd, WM_USER + 18, 0, 0
    End If
End Sub

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

GetObject([Pathname] [Class])

Возвращает ссылку на объект, обеспечиваемый компонентом ActiveX

Параметры
Функция содержит именованные аргументы


Pathname Необязательный аргумент-значение типа Variant(String). Полная спецификация пути и имя файла, содержащего отыскиваемый объект. В случае, если аргумент опущен, параметр Class является обязательным
Class Необязательный аргумент-значение типа Variant(String).Строка, отражающая класс объекта

Параметр Class имеет синтаксис appname.objecttype, в котором присутствуют следующие элементы:


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

Примечания

Функция GetObject применяется для доступа в объекту ActiveX, находящемуся в файле, и для присваивания этого объекта объектной переменной. Для присваивания объекта, возвращенного функцией GetObject, объектной переменной используется оператор Set. Например:

Dim CADObject As Object
Set CADObject = GetObject("C:CADSCHEMA.CAD")

При исполнении данного кода производится запуск приложения, указанного параметром pathname, и активизация объекта в заданном файле.

Если значением параметра pathname является пустая строка («»), функция GetObject возвращает новый экземпляр объекта заданного типа. В случае, если параметр pathname опущен, функция GetObject возвращает активный в данный момент объект заданного типа. Если объекта указанного типа не существует, возникает ошибка.

Ряд приложений допускают активизацию части файла. Для этого нужно добавить после имени файла восклицательный знак (!) и поместить вслед за ним строку, задающую ту часть файла, которую требуется активизировать. Дополнительные сведения относительно составления такой строки смотрите в документации на то приложение, которое создает объект.

К примеру, в графическом приложении может присутствовать несколько уровней рисования, хранящихся в файле. Для активизации уровня под названием SCHEMA.CAD можно воспользоваться следующим кодом:

Set LayerObject = GetObject("C:CADSCHEMA.CAD!Layer3")

В тех случаях, когда не указан класс объекта (параметр class), автоматизация (Automation) находит приложение, которое нужно запустить, на основе заданного имени файла. Однако ряд файлов могут поддерживать несколько классов объектов. Например, приложение для рисования может поддерживать три различных типа объектов: объект Application, объект Drawing и объект Toolbar, которые являются частью одного файла. Для указания требуемого объекта нужно указать необязательный параметр class. Например:

Dim MyObject As Object
Set MyObject = GetObject("C:DRAWINGSSAMPLE.DRW", "FIGMENT.DRAWING")

В приведенном примере FIGMENT – это имя графического приложения, а DRAWING – один из поддерживаемых этим приложением типов объектов.

После активизации объекта, производится ссылка на него в коде с использованием определенной объектной переменной,. В предыдущем примере доступ к свойствам и методам нового объекта осуществляется с помощью объектной переменной MyObject. Например:

MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:DRAWINGSSAMPLE.DRW"

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

Если объект производит само регистрацию в качестве объекта с единственным экземпляром, то, независимо от числа обращений к функции CreateObject, будет создан только один экземпляр такого объекта. В случае наличия только одного экземпляра объекта, функция GetObject, при ее вызове с использованием синтаксиса с указанием пустой строки («»), всегда возвращает один и тот же экземпляр, а при отсутствии параметра pathname возникает ошибка. Функцию GetObject можно применять для получения ссылки на класс, созданный в Visual Basic.

Пример

'Пример использования функции GetObject
' В данном примере функция GetObject создает ссылку
' на конкретный лист (MyXL) в Microsoft Excel.
' Для того, чтобы сделать Microsoft Excel видимым,
'закрыть его и т. д., используется свойство 
' Application рабочего листа.
' С помощью двух вызовов API процедура 
' Sub DetectExcel ищет Microsoft Excel и,
' если он выполняется, вводит его в таблицу выполняемых
' объектов (Running Object Table).
' Первый вызов GetObject приводит к ошибке,
' если Microsoft Excel еще не запущен.
' В этой программе ошибка приводит к установке значения True для флага ExcelWasNotRunning.
' Второй вызов GetObject указывает открываемый
' файл. Если Microsoft Excel не был запущен, то в
' результате второго вызова функции это приложение
' запускается, при этом возвращается ссылка на лист,
' соответствующий указанному файлу. Файл mytest.xls
' должен существовать в указанном каталоге; в противном ' случае возникает ошибка Visual Basic «Automation error»
' (Ошибка автоматизации). Далее в программе делаются
' видимыми окно Microsoft Excel и окно, содержащее
' указанный лист. И наконец, если Microsoft Excel
' не выполнялся при запуске этой программы,
' метод Quit объекта Application
' закрывает Microsoft Excel. Если это приложение
' выполнялось до запуска данной программы, попытка
' закрыть его не предпринимается. Ссылка на лист
' освобождается путем установки ее значения в Nothing
' Описываем необходимые процедуры API:
Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName as String, _
 ByVal lpWindowName As Long) As Long

Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd as Long,ByVal wMsg as Long, _
 ByVal wParam as Long, _
 ByVal lParam As Long) As Long

Sub GetExcel()
 Dim MyXL As Object  ' Переменная для сохранения
 ' ссылки на Microsoft Excel
 Dim ExcelWasNotRunning As Boolean  ' Флаг для окончательного освобождения.

' Проверка, выполняется ли Microsoft Excel
 On Error Resume Next ' Отложенный перехват ошибок.
' Функция GetObject, вызванная без указания первого параметра, 
' возвращает ссылку на экземпляр приложения. Если приложение
' не запущено, возвращается ошибка
 Set MyXL = Getobject(, "Excel.Application")
 If Err.Number <> 0 Then ExcelWasNotRunning = True
 Err.Clear ' Очищаем объект Err на случай ошибки.

' Проверка Microsoft Excel. Если Microsoft Excel выполняется,
' он вводится в таблицу выполняемых объектов (Running Object table)
 DetectExcel

' Задаем в объектной переменной ссылку на открываемый файл
 Set MyXL = Getobject("c:vb4MYTEST.XLS")

' Делаем видимым Microsoft Excel с помощью его свойства Application. 
' Делаем видимым окно, содержащее файл, с помощью 
' коллекции Windows, задаваемой объектной ссылкой MyXL
 MyXL.Application.Visible = True
 MyXL.Parent.Windows(1).Visible = True
  Do manipulations of your file here.
 ' ...
' Если этот экземпляр Microsoft Excel не выполнялся при запуске данной
' программы, закрываем его с помощью метода Quit свойства Application. 
' Отметим, что при попытке выхода из Microsoft Excel
' появляется мерцание строки заголовка и отображается сообщение, запрашивающее вас
' о необходимости сохранения файлов
 If ExcelWasNotRunning = True Then 
 MyXL.Application.Quit
 End IF

 Set MyXL = Nothing ' Освобождаем ссылку на
 ' приложение и электронную таблицу
End Sub

Sub DetectExcel()
' Процедура находит выполняемый Excel и регистрирует его
 Const WM_USER = 1024
 Dim hWnd As Long
' Если Excel выполняется, этот вызов API возвращает его дескриптор
 hWnd = FindWindow("XLMAIN", 0)
 If hWnd = 0 Then  ' 0 означает, что Excel не выполняется
 Exit Sub
 Else 
 ' Excel выполняется, поэтому используйте
 функцию API SendMessage, чтобы ввести его в таблицу выполняемых объектов (Running Object Table)
 SendMessage hWnd, WM_USER + 18, 0, 0
 End If
End Sub

Категория
Функции работы с объектами

Excel VBA GETOBJECT Function

We can use the GetObject function in VBA in MS Excel to access an ActiveX object from the Excel file and then assign the object to an object variable. To use OLE (Object Linking and Embedding) or COM (Compound Object Module) technology to control any Microsoft application like MS Word, MS Outlook, MS PowerPoint, Internet Explorer, etc., we can use the VBA GETOBJECT function.

We use the CreateObject function to create the object, and the GETOBJECT function returns the reference to the object.

Table of contents
  • Excel VBA GETOBJECT Function
    • Syntax for GETOBJECT Function
    • Example of Excel VBA GETOBJECT Function
    • Things to Remember
    • Recommended Articles

VBA-GETOBJECT

Syntax for GETOBJECT Function

VBA GetObject syntax

The GETOBJECT function has these named arguments:

  1. Pathname: We need to specify the full path and the file name containing the object to retrieve. It is an optional argument. Both arguments in the GetObject function are optional, but if ‘pathname’ omits, the second argument, ‘class’, is required.
  2. Class: This is also an optional argument, as specified earlier also. It accepts a string representing the class of the object.

We use the syntax ‘appname.objecttype’ to specify the ‘class’ argument.

  1. Appname: We need to specify the application name to provide the object.
  2. Object type: We specify the type of class of object to create.

Example of Excel VBA GETOBJECT Function

You can download this VBA GetObject Template here – VBA GetObject Template

Suppose we have a word document containing 3 tables.

VBA GetObject Example 1

VBA GetObject Example 1-1

We want to write a VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more that will import all the tables in the document to the Excel sheet. We will need to use the CreateObjectCreateObject, as the name implies, is a function that will create the aforementioned object from Excel VBA. When you create an object using the CreateObject function, it is referred to as late binding.read more and GetObject functions in VBA to do the same.

Steps would be:

  • Create an Excel file and save the file with the .xlsm excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more (Excel Macro-Enabled Workbook) as we will need to run the VBA code (a macro).
  • Open the basic visual editor with a shortcut key (Alt+F11) or use the ‘Visual Basic’ command in the ‘Code’ group in the Developer tab in excelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more.
  • Double click on ‘ThisWorkbook’ on the left side of the VBA editorVBA ThisWorkbook refers to the workbook on which the users currently write the code to execute all of the tasks in the current workbook. In this, it doesn’t matter which workbook is active and only requires the reference to the workbook, where the users write the code.read more and choose ‘Workbook’ from the list shown on the screen’s top.

VBA GetObject Example 1-2

  • Choose ‘Open’ from the list.

VBA GetObject Example 1-3

  • Now, we need to write the code in between these two lines.

VBA GetObject Example 1-5

  • First, we will declare variables to hold the objects (MS Word Document and MS Word Application object) and a ‘String Variable’ to hold the document’s name from where we need to extract the tables.

VBA GetObject Example 1-4

  • For error handling, we will add one statement. This statement tells the VBA program to ignore the error and resume the execution with the next line of code. “On Error Resume NextVBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error.read more” statement does not fix the runtime errors, but it simply means that program execution will continue from the line following the line that caused the error.

VBA GetObject Example 1-6

  • Now we will use the GetObject function to access the current instance of the Word Application Object.

VBA GetObject Example 1-7

  • If there is no current MS Word application instance, or the ActiveX component cannot create an object or return reference to this object, then error 429. For this, we will add two lines in the code. After handling the error, we need to create an instance of the MS Word Application object using the CreateObject function.

VBA GetObject Example 1-8

  • To make the MS Word Application visible, we will change the visible property of the ‘WdApp’ object to TRUE.

VBA GetObject Example 1-9

  • We need to find the location and file name of the word document from which we want to import the tables into an excel sheet and assign the same to the “strDocName” To find the name and location, we can check out the properties of the file.

To open the ‘Properties’ dialog box, select the file and press ‘Alt+Enter.’

VBA GetObject Example 1-10

Get Object Example 1-11

  • If the file does not exist in the specified location, the code returns the message stating, “The file Marks Details was not found in the folder path.” The title would be “Sorry, that document name does not exist.”

Get Object Example 1-12

  • Now we need to activate the MS Word Application and assign the variable ‘wddoc’ with the word document having the file name stored in the ‘strDocName.’

Get Object Example 1-13

  • If the file is not open, we need to open the document and activate the app.

Get Object Example 1-14

  • After activating the word document, we need to access the tables in the document. To do the same, we will create some variables.

Get Object Example 1-15

Tble is the integer variable that will store the count of tables in the document.

rowWd is the long variable that will store the number of rows in a table.

colWd is the long variable, storing the number of columns in a particular table.

  • We need to count the number of tables in the document, and if they are notable in the document, then we will display a message box to the user that says “No Tables found in the Word document.”

Get Object Example 1-16

  • We will run a ‘For’ VBA loopAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more for several tables to access tables in the document and write the content in the Excel sheet. Within this VBA loopA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more, we will run nested ‘for’ loops for accessing every row and every column in the row.

Get Object Example 1-17

  • As we do not want to save the document and quit the application, we should also release the system’s memory. To do the same, we will write the following code.

Get Object Example 1-18

Now, whenever we open the excel file, the file is updated with table content from the word document.

VBA Get-Object Example 1-19

Code:

Private Sub Workbook_Open()

Rem Declaring Object variables to access object created by GETOBJECT
Dim WdApp As Object, wddoc As Object
Rem Declaring a string variable to access the Word document
Dim strDocName As String

Rem Error handling
On Error Resume NextVBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error.read more

Rem Activating MS Word if it is already opened
Set WdApp = GetObject(, "Word.Application")

If Err.Number = 429 Then
Err.Clear
Rem Creating a Word application object if MS Word is not already opened
Set WdApp = CreateObject("Word.Application")
End If

WdApp.Visible = True

strDocName = "C:UsersCBA7_01DesktopMarks Details.docx"

Rem Checking relevant directory for the relevant document
Rem If not found then informing the user and closing the program
If Dir(strDocName) = "" Then
MsgBox "The file " & strDocName & vbCrLf & "was not found in the folder path" & vbCrLf & "C:UsersCBA7_01.", _vbExclamation, "Sorry, that document name does not exist."
Exit Sub
End If

WdApp.Activate

Set wddoc = WdApp.Documents(strDocName)

If wddoc Is Nothing Then Set wddoc = WdApp.Documents.Open("C:UsersCBA7_01DesktopMarks Details.docx")
wddoc.Activate

Rem Defining variables to access the tables in the word document
Dim Tble As Integer
Dim rowWd As Long
Dim colWd As Integer
Dim x As Long, y As Long
x = 1
y = 1

With wddoc
Tble = wddoc.Tables.Count
If Tble = 0 Then
MsgBox "No Tables found in the Word document", vbExclamation, "No Tables to Import"
Exit Sub
End If

Rem Starting the looping process to access tables and their rows, columns
For i = 1 To Tble
With.Tables(i)
For rowWd = 1 To .Rows.Count
For colWd = 1 To .Columns.Count
Cells(x, y) = WorksheetFunction.Clean(.cell(rowWd, colWd).Range.Text)
Rem Accessing next column
y = y + 1
Next colWd
Rem Going to next row and start from column 1
y = 1
x = x + 1
Next rowWd
End With
Next
End With

Rem we do not need to save the word document
wddoc.Close Savechanges:=False
Rem we quit MS Word application
WdApp.Quit
Rem We finally release system memory allocated for the 2 object variables
Set wddoc = Nothing
Set WdApp = Nothing

End Sub

Things to Remember

  1. A single-instance object is available for which only one instance of the object generates, regardless of the number for which CreateObject is run. For example, the GetObject function always returns the same instance when called with a string of zero length, and an error comes if it does not mention the ‘pathname’ argument.
  2. We cannot use GetObject to access a reference to a class created with VBA.
  3. Suppose there is no active instance of the MS Word Application, or we do not want the object initiated with a file already loaded. In that case, we first use the CreateObject function to create the object and then use the GetObject function to access the object.

Recommended Articles

This article has been a guide to VBA GetObject. Here, we discuss how the GetObject function returns an object’s reference in Excel VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA IF Not
  • VBA INSTRREV
  • VBA FileSystemObject
  • VBA Option Explicit

Содержание

  1. GetObject function
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. Функция GetObject
  8. Синтаксис
  9. Замечания
  10. Пример
  11. См. также
  12. Поддержка и обратная связь
  13. GetObject Function

GetObject function

Returns a reference to an object provided by an ActiveX component.

Syntax

GetObject([ pathname ], [ class ])

The GetObject function syntax has these named arguments:

Part Description
pathname Optional; Variant (String). The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class Optional; Variant (String). A string representing the class of the object.

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.

Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:

When this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated.

If pathname is a zero-length string («»), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate part of a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file that you want to activate. For information about how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD :

If you don’t specify the object’s class, automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

In the example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports. After an object is activated, you reference it in code by using the object variable you defined. In the preceding example, you access properties and methods of the new object by using the object variable MyObject. For example:

Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don’t want the object started with a file loaded, use the CreateObject 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. With a single-instance object, GetObject always returns the same instance when called with the zero-length string («») syntax, and it causes an error if the pathname argument is omitted. You can’t use GetObject to obtain a reference to a class created with Visual Basic.

Example

This example uses the GetObject function to get a reference to a specific Microsoft Excel worksheet ( MyXL ). It uses the worksheet’s Application property to make Microsoft Excel visible, to close it, and so on.

Using two API calls, the DetectExcel Sub procedure looks for Microsoft Excel, and if it is running, enters it in the Running Object Table.

The first call to GetObject causes an error if Microsoft Excel isn’t already running. In the example, the error causes the ExcelWasNotRunning flag to be set to True.

The second call to GetObject specifies a file to open. If Microsoft Excel isn’t already running, the second call starts it and returns a reference to the worksheet represented by the specified file, mytest.xls. The file must exist in the specified location; otherwise, the Visual Basic error Automation error is generated.

Next, the example code makes both Microsoft Excel and the window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code uses the Application object’s Quit method to close Microsoft Excel. If the application was already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.

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.

Источник

Функция GetObject

Возвращает ссылку на объект, предоставляемый компонентом ActiveX.

Синтаксис

GetObject([ pathname ], [ класс ])

Синтаксис функции GetObject имеет следующие именованные аргументы:

Part Описание
путь Необязательный элемент, Variant (String). Полный тип и имя файла, содержащий объект, который требуется получить. Если аргумент имя_пути пропущен, класс является обязательным.
класс Необязательный элемент, Variant (String). Строка, представляющая класс объекта.

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

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

Замечания

Используйте функцию GetObject для доступа к объекту ActiveX из файла и назначения объекта объектной переменной. Используйте инструкцию Set , чтобы назначить объект, возвращенный GetObject , переменной объекта. Например:

При выполнении этого кода запускается приложение, связанное с указанным именем пути , и активируется объект в указанном файле.

Если имя_пути имеет пустую строку («»), GetObject возвращает новый экземпляр объекта указанного типа. Если аргумент имя_пути пропущен, функция GetObject возвращает текущий активный объект указанного типа. Если объект указанного типа не существует, происходит ошибка.

Некоторые приложения разрешают активировать часть файла. Добавьте восклицательный знак (!) в конец имени файла и следуйте за ним со строкой, определяющей часть файла, которую требуется активировать. Сведения о создании этой строки см. в документации по приложению, создавшего объект .

Например, в приложении рисования можно иметь несколько уровней для рисунка, сохраненного в файле. Можно использовать следующий код для активации слоя в документе с именем SCHEMA.CAD :

Если не указать класс объекта, автоматизация определяет приложение для запуска и объект для активации на основе указанного имени файла. Некоторые файлы, однако, могут поддерживать более одного класса объекта. Например, рисунок может поддерживать три различных типа объектов: объект Application, объект Drawing и объект Toolbar, каждый из которых является частью одного и того же файла. Чтобы указать, какой объект в файле требуется активировать, используйте необязательный аргумент класс. Например:

В примере FIGMENT — это имя приложения для рисования и DRAWING один из поддерживаемых типов объектов. После активации объекта вы ссылаетесь на него в коде с помощью определенной объектной переменной. В предыдущем примере доступ к свойствам и методам нового объекта выполняется с помощью объектной переменной MyObject. Например:

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

Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject. При использовании объекта с одним экземпляром Метод GetObject всегда возвращает один и тот же экземпляр при вызове с синтаксисом строки нулевой длины («») и вызывает ошибку, если аргумент pathname пропущен. Вы не можете использовать GetObject для получения ссылки на класс, созданный с помощью Visual Basic.

Пример

В этом примере функция GetObject используется для получения ссылки на определенный лист Microsoft Excel ( MyXL ). Она использует свойство Application листа, чтобы сделать видимым Microsoft Excel, закрыть его и т. п.

Используя два вызова API, DetectExcel процедура Sub ищет Microsoft Excel и, если она выполняется, вводит ее в таблицу выполняющихся объектов.

Первый вызов функции GetObject приводит к возникновению ошибки, если Microsoft Excel не выполняется. В этом примере ошибка приводит ExcelWasNotRunning к тому, что флагу присваивается значение True.

Второй вызов GetObject задает открытие файла. Если Microsoft Excel еще не выполняется, второй вызов запускает его и возвращает ссылку на лист, представленный указанным файлом, mytest.xls. Файл должен находиться в указанном расположении; В противном случае возникает ошибка Automation error Visual Basic.

Затем пример кода делает видимыми как Microsoft Excel, так и окно, содержащее указанный лист. Наконец, если не выполняется предыдущая версия Microsoft Excel, в коде используется метод Quit объекта Application для закрытия Microsoft Excel. Если приложение уже выполнялось, попытка закрыть его не предпринимается. Сама ссылка освобождается путем установки для нее значения Nothing.

См. также

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

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

Источник

GetObject 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.

Returns a reference to an object provided by an ActiveX component.

The GetObject function syntax has these arguments:

Optional. Variant ( String). The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.

Optional. Variant ( String). A string representing the class of the object.

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.

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.

Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated.

If pathname is a zero-length string («»), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate part of a file. Add an exclamation point ( !) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD :

If you don’t specify the object’s class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

In the example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

Once an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object by using the object variable MyObject . For example:

Note: Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don’t want the object started with a file loaded, use the CreateObject 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. With a single-instance object, GetObject always returns the same instance when called with the zero-length string («») syntax, and it causes an error if the pathname argument is omitted. You can’t use GetObject to obtain a reference to a class created with Visual Basic.

Источник

VBA GetObject

Excel VBA GetObject

VBA GetObject, as the name, seems like we need to create a code for getting or creating an object. But in fact, it is the process of getting the Tables from any word to excel file. In VBA GetObject, we fetch the data from a word file by putting the location where it is kept and append any number of tables from that Word into the Excel sheet.

Syntax of VBA GetObject

Syntax of GetObject

Syntax is explained as shown below:

  • PathName = Here we will be giving the path to the Word document where it is kept. This field is optional.
  • Class = Here, we need to define the Class of Object function. This one is too optional. But if we are not defining the PathName in the syntax then Class will be must to define.

Both the arguments of the syntax are optional. But anyone of them should be defined.

Here, we will be using appname.objecttype to define the Class. AppName will be the application or type of file from which we will be fetching the data and Objecttype will be kind of file application we will be using.

Example of GetObject Function in Excel VBA

We will be seeing, how to fetch the data which is in the form of Table in a word document and append that data in Excel worksheet.

You can download this VBA GetObject Excel Template here – VBA GetObject Excel Template

For this, we require such data in word file. Here, we are having a word file below, which has 2 tables of Employee name and Employee ID.

VBA GetObject 1

We have saved this file somewhere in our local drive which is easy to access. Follow the below steps to use GetObject function in Excel VBA.

Step 1: Go to VBA window and open a Module from the Insert menu tab as shown below.

VBA GetObject 1-2

Step 2: In the newly opened Module, write the subcategory of VBA GetObject or you can choose any other name as per need.

VBA GetObject 1-3

Step 3: First, define the 2 Object variable to access the Object prepared by VBA GetObject.

VBA GetObject 1-4

Step 4: We would need another variable for which we will store the location of File as String.

VBA GetObject 1-5

Step 5: To avoid any break if an error occurs we will keep resuming the next step.

VBA GetObject 1-6

Step 6: Now we would use GetObject function and set it as WordFile object. Keeping Path blank, we will define the Class as Word.Application where Word is the application of Microsoft.

VBA GetObject 1-7

Step 7: To avoid error number 429 which usually occurs in this case, we will clear it as it happens.

VBA GetObject 1-8

Step 8: Now make the created Object variable WordFile visible.

Object variable WordFile

Step 9: As we haven’t defined the path, so we will assign file location to StrDoc along with the extension.

Assign file location

Step 10: If we did not find anything in the word file, then we should be getting a message prompting that “No Data Available” or “Document Not Found”. And this would be done in If-End If loop.

VBA GetObject 1-11

Step 11: Now activate the Word file.

Activate Word file

Step 12: Do the same procedure for setting WordDoc as well. If WordDoc is nothing then we will open the file from the location where it is kept.

Setting WordDoc

Step 13: Now we will need to define the variables which will help in accessing the table from Word document. By this we will be creating a Table with Rows and Columns.

VBA GetObject 1-14

Step 14: As we all know the vertex of cells is 2 dimensional. So starting from 1st cell, we would need 2 variable where we will define the location from where we need to start our table in Excel. Here, we have considered that position at (1, 1) which is at 1st cell of the sheet.

VBA GetObject 1-15

Step 15: At this stage, we need to check the number of tables in Word file. And if there are no tables found then we should be getting the message for that.

Check the Number of tables

Step 16: In this step, we need to access the table from Word document and map that in Excel file. For this, we will use For loop for each row and column.

For loop

Step 17: At last we will quit the document once it appends the data from word to excel file without saving the file.

VBA GetObject 1-18

Step 18: Now Run the above code by pressing the F5 key or by clicking on the Play button.

We will see, the data which we have seen at the starting of the article which was separate in 2 different tables, is now appended in a single table in the excel sheet.

VBA GetObject 1-19

Below is the complete code in one sequence:

Code:

Sub VBA_GetObject()

Dim WordFile As Object
Dim WordDoc As Object
Dim StrDoc As String

On Error Resume Next
Set WordFile = GetObject(, "Word.Application")

If Err.Number = 429 Then
Err.Clear
Set WordFile = CreateObject("Word.Application")
End If

WordFile.Visible = True
StrDoc = "D:InputTest.docx"

If Dir(StrDoc) = "" Then
MsgBox StrDoc & vbCrLf & "Not Found in mentioned Path" & vbCrLf & "C:Input Location", vbExclamation, "Document name not found"
Exit Sub
End If

WordFile.Activate

Set WordDoc = WordFile.Documents(StrDoc)

If WordDoc Is Nothing Then Set WordDoc = WordFile.Documents.Open("D:InputTest.docx")
WordDoc.Activate

  Dim Tble As Integer
  Dim RowWord As Long
  Dim ColWord As Integer
  Dim A As Long
  Dim B As Long
A = 1
B = 1

With WordDoc
Tble = WordDoc.Tables.Count
If Tble = 0 Then
MsgBox "No Tables Avaiable", vbExclamation, "Nothing To Import"
Exit Sub
End If

For i = 1 To Tble
With .Tables(i)
For RowWord = 1 To .Rows.Count
For ColWord = 1 To .Columns.Count
Cells(A, B) = WorksheetFunction.Clean(.cell(RowWord, ColWord).Range.Text)

B = B + 1
Next ColWord

B = 1
A = A + 1
Next RowWord
End With
Next
End With

WordDoc.Close Savechanges:=False

WordFile.Quit

Set WordDoc = Nothing
Set WordFile = Nothing

End Sub

Pros of Excel VBA GetObject

  • It is quite useful in importing the big set of data from word file to excel file.
  • We can import any kind of data from any kind of file just by changing the extension of it.

Things to Remember

  • Close all the word files before running the code.
  • Give the proper extension to the file which is being used.
  • GetObject cannot be used to access the reference to class.

Recommended Articles

This is a guide to VBA GetObject. Here we discuss how to use GetObject function in VBA to fetch the data from a word file into the excel sheet along with a practical example and downloadable excel template. You can also go through our other suggested articles –

  1. VBA GetOpenFileName
  2. VBA Workbook Open
  3. VBA RGB
  4. VBA On Error Resume Next
Private Sub Кнопка0_Click()
Dim objExcel As Object
Dim objWorkbook As Object
Dim strFileName As String

On Error Resume Next
strFileName =  "D:List.xlsx"'тут уж придумай сам откуда брать путь
    If Len(Dir$(strFileName)) = 0 Then MsgBox "Нет Файла!": Exit Sub
Set objExcel = GetObject(, "Excel.Application") 'получаем объект, если он открыт (Excel запущен уже)
    If objExcel Is Nothing Then 'не получили (не запущен)
        Err.Clear 'очищаем от ошибки
        Set objExcel = CreateObject("Excel.Application") 'создаём объект (запускаем Excel)
            If objExcel Is Nothing Then Err.Clear: MsgBox "Не установлен MS Excel!", vbCritical, "Ошибка": Exit Sub 'без комментариев
    End If
    With objExcel
        .DisplayAlerts = False
'        .ActivateMicrosoftApp 4& 'xlMicrosoftAccess = 4'это, если нужно переключиться на окно Access
        Set objWorkbook = .Workbooks.Item(Mid(strFileName, InStrRev(strFileName, "") + 1)).Windows(1)
            If objWorkbook Is Nothing Then 'не получили, книга не открыта
                Err.Clear 'очищаем от ошибки
                Set objWorkbook = .Workbooks.Open(strFileName, 0) '0 - ссылки не обновляем при открытии
                objWorkbook.UpdateLink objWorkbook.LinkSources
                    If Err.Number = 1004 Then 'не нашли файлы для обновления ссылок
                        Err.Clear 'очищаем от ошибки
                            If MsgBox("Обновить ссылки?", vbQuestion Or vbYesNo) = vbYes Then
                                Excel_UpdateLinks objWorkbook
                            Else
                                MsgBox "Внимание!" & vbNewLine & "Ссылки в книге """ & _
                                    Mid(strFileName, InStrRev(strFileName, "") + 1) & """ не обновлены!", vbInformation, "Обновление ссылок"
                            End If
                    ElseIf Err Then
                        MsgBox "Ошибка: " & Err.Number & vbNewLine & Err.Description, vbCritical, "Обновление ссылок"
                        Err.Clear 'очищаем от ошибки
                        Exit Sub 'Вообще надо посмотреть, что за ошибка, попробовать обработать...
                    End If
                With objWorkbook
                    .Visible = True
                    .Activate
                End With
            End If
        .Visible = True
            If Not .UserControl Then .UserControl = True
            If .Windows.Count > 0 Then .Windows(.Windows.Count).Activate
        Call SetForegroundWindow(.hWnd) 'это, если нужно лицезреть Excel
    End With
Set objWorkbook = Nothing
Set objExcel = Nothing
End Sub

Private Function Excel_UpdateLinks(objWorkbook As Object) As Boolean
Dim arrLinks As Variant
Dim i As Long, lngRetVal As Long
Dim strFileName As String
Dim dlgOpenFile As Object 'FileDialog

arrLinks = objWorkbook.LinkSources(1&) 'xlExcelLinks=1
    If Not IsEmpty(arrLinks) Then
        If IsArray(arrLinks) Then
                For i = 1 To UBound(arrLinks)
                    If Len(Dir$(arrLinks(i))) = 0 Then
                        lngRetVal = MsgBox("Не нашли файл по ссылке " & """" & arrLinks(i) & """" & vbNewLine & _
                                           "Искать бум?", vbQuestion Or vbYesNo, "Обновление ссылок")
                            If lngRetVal = vbYes Then
                                strFileName = arrLinks(i) 'получаем ссылку (путь) на файл
                                    If Len(Dir$(strFileName)) = 0 Then 'проверяем на существование (если нет файла, то идём к циклу)
                                        Do While Len(Dir$(strFileName, vbDirectory)) = 0 'ищем путь (папку)
                                            strFileName = Left$(strFileName, InStrRev(strFileName, "") - 1)
                                                If InStr(1, strFileName, "") = 0 Then strFileName = CurDir: Exit Do 'если не нашли папку, получим текущий каталог
                                        Loop
                                    End If
                                Set dlgOpenFile = Application.FileDialog(3&) 'msoFileDialogFilePicker
                                    With dlgOpenFile
                                        .InitialFileName = strFileName
                                        .AllowMultiSelect = False
                                        .Title = "Укажите файл для восстановления ссылки"
                                            If .Show = -1 Then
                                                objWorkbook.ChangeLink arrLinks(i), .SelectedItems(1), 1& 'xlExcelLinks
                                            Else
                                                MsgBox "Не указано новое положение файла для восстановления ссылки!" & vbNewLine & _
                                                        "Ссылки не будут обновлены.", vbInformation, "Обновление ссылок"
                                                Erase arrLinks
                                                Exit Function
                                            End If
                                    End With
                                strFileName = ""
                            Else
                                MsgBox "Не указано новое положение файла для восстановления ссылки!" & vbNewLine & _
                                        "Ссылки не будут обновлены.", vbInformation, "Обновление ссылок"
                                Erase arrLinks
                                Exit Function
                            End If
                    End If
                Next i
            objWorkbook.UpdateLink objWorkbook.LinkSources 'обновим ссылки в книге
            Erase arrLinks
        End If
    End If
Excel_UpdateLinks = True
Set dlgOpenFile = Nothing
End Function

  • Excel VBA GetObject

Excel VBA GetObject

VBA GetObject, как следует из названия, похоже, что нам нужно создать код для получения или создания объекта. Но на самом деле это процесс получения таблиц из любого слова в файл Excel. В VBA GetObject мы извлекаем данные из файла слов, помещая место их хранения и добавляем любое количество таблиц из этого Word в лист Excel.

Синтаксис VBA GetObject

Синтаксис объясняется как показано ниже:

  • PathName = Здесь мы будем указывать путь к документу Word, где он хранится. Это поле не является обязательным.
  • Class = Здесь нам нужно определить функцию Class of Object. Этот слишком необязательный. Но если мы не определяем PathName в синтаксисе, то Class должен быть определен.

Оба аргумента синтаксиса являются необязательными. Но любой из них должен быть определен.

Здесь мы будем использовать appname.objecttype для определения класса. AppName будет приложением или типом файла, из которого мы будем извлекать данные, а Objecttype будет своего рода файловым приложением, которое мы будем использовать.

Пример функции GetObject в Excel VBA

Мы увидим, как получить данные в виде таблицы в виде документа Word и добавить эти данные в таблицу Excel.

Вы можете скачать этот шаблон VBA GetObject Excel здесь — Шаблон VBA GetObject Excel

Для этого нам требуются такие данные в словесном файле. Здесь у нас есть файл слов ниже, который имеет 2 таблицы имени сотрудника и идентификатора сотрудника.

Мы сохранили этот файл где-то на нашем локальном диске, к которому легко получить доступ. Выполните следующие шаги, чтобы использовать функцию GetObject в Excel VBA.

Шаг 1. Откройте окно VBA и откройте модуль на вкладке меню « Вставка », как показано ниже.

Шаг 2: В открывшемся модуле напишите подкатегорию VBA GetObject или вы можете выбрать любое другое имя по необходимости.

Шаг 3. Сначала определите переменную 2 Object для доступа к объекту, подготовленному VBA GetObject.

Шаг 4: Нам понадобится другая переменная, для которой мы будем хранить расположение File как String.

Шаг 5: Чтобы избежать перерыва в случае возникновения ошибки, мы продолжим выполнение следующего шага.

Шаг 6: Теперь мы будем использовать функцию GetObject и установить ее как объект WordFile . Оставляя путь пустым, мы определим класс как Word.Application, где Word является приложением Microsoft.

Шаг 7: Чтобы избежать ошибки номер 429, которая обычно возникает в этом случае, мы очистим ее, как это происходит.

Шаг 8: Теперь сделайте созданную переменную объекта WordFile видимой.

Шаг 9: Поскольку мы не определили путь, мы назначим расположение файла для StrDoc вместе с расширением.

Шаг 10: Если мы не нашли ничего в словесном файле, мы должны получить сообщение с запросом «Нет данных» или «Документ не найден». И это будет сделано в цикле If-End If.

Шаг 11: Теперь активируйте файл Word.

Шаг 12: Проделайте ту же процедуру для настройки WordDoc. Если WordDoc — это ничто, мы откроем файл из того места, где он хранится.

Шаг 13: Теперь нам нужно определить переменные, которые помогут в доступе к таблице из документа Word. По этому мы будем создавать таблицу со строками и столбцами.

Шаг 14: Как мы все знаем, вершина клеток является двухмерной. Итак, начиная с 1- й ячейки, нам понадобятся 2 переменные, в которых мы определим место, откуда нам нужно начать нашу таблицу в Excel. Здесь мы рассмотрели ту позицию в (1, 1), которая находится в 1- й ячейке листа.

Шаг 15: На этом этапе нам нужно проверить количество таблиц в файле Word. И если таблицы не найдены, мы должны получить сообщение об этом.

Шаг 16. На этом шаге нам нужно получить доступ к таблице из документа Word и отобразить ее в файле Excel. Для этого мы будем использовать цикл For для каждой строки и столбца.

Шаг 17: Наконец, мы выйдем из документа, как только он добавит данные из Word в файл Excel без сохранения файла.

Шаг 18: Теперь запустите приведенный выше код, нажав клавишу F5 или нажав кнопку Play.

Мы увидим, что данные, которые мы видели в начале статьи, которые были разделены на две разные таблицы, теперь добавлены в одну таблицу в листе Excel.

Ниже приведен полный код в одной последовательности:

Код:

 Sub VBA_GetObject () Dim WordFile как объект Dim WordDoc как объект Dim StrDoc как строка при ошибке Возобновить следующее Установить WordFile = GetObject (, "Word.Application") Если Err.Number = 429, то Err.Clear Установить WordFile = CreateObject ("Word. Приложение ") End If WordFile.Visible = True StrDoc =" D:  Input  Test.docx "If Dir (StrDoc) =" "Тогда MsgBox StrDoc & vbCrLf &" Не найдено в указанном пути "& vbCrLf &" C:  Расположение ввода ", vbExclamation, " Имя документа не найдено "Выйти из Sub End, если WordFile.Activate Установить WordDoc = WordFile.Documents (StrDoc) Если WordDoc ничего не значит, то установить WordDoc = WordFile.Documents.Open (" D:  Input  Test. docx ") WordDoc. Активировать Dim Tble как целое число Dim RowWord как длинное Dim ColWord как целое число Dim A как длинное Dim B как длинное A = 1 B = 1 с WordDoc Tble = WordDoc.Tables.Count Если Tble = 0, то MsgBox" Нет таблиц Avaiable ", vbExclamation, " Ничего не импортировать "Выход из под-конца, если для i = 1 в таблицу с .Tables (i) для RowWord = 1 в .Rows.Count для ColWord = 1 в .Columns.Count Ячейки (A, B) = WorksheetFunctio n.Clean (.cell (RowWord, ColWord) .Range.Text) B = B + 1 Следующий ColWord B = 1 A = A + 1 Следующий конец RowWord со следующим концом с WordDoc. Закрыть Сохранить изменения: = False WordFile.Quit Установить WordDoc = Nothing Set WordFile = Nothing End Sub 

Плюсы Excel VBA GetObject

  • Это очень полезно при импорте большого набора данных из файла Word в файл Excel.
  • Мы можем импортировать данные любого типа из любого файла, просто изменив его расширение.

То, что нужно запомнить

  • Закройте все файлы слов перед запуском кода.
  • Дайте правильное расширение файла, который используется.
  • GetObject нельзя использовать для доступа к ссылке на класс.

Рекомендуемые статьи

Это руководство по VBA GetObject. Здесь мы обсудим, как использовать функцию GetObject в VBA для извлечения данных из файла слов в таблицу Excel вместе с практическим примером и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. VBA GetOpenFileName
  2. Панель инструментов KPI в Excel
  3. VBA Workbook Open
  4. Excel Word Count
  5. Excel VBA при ошибке возобновить следующий

Понравилась статья? Поделить с друзьями:
  • Excel vba get row from range
  • Excel vba get range names
  • Excel vba get all sheets
  • Excel vba listobject range
  • Excel vba function with no return value