Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше
Примечание: Функция, метод, объект или свойство, описанные в данном разделе, отключаются, если служба обработки выражений Microsoft Jet выполняется в режиме песочницы, который не позволяет рассчитывать потенциально небезопасные выражения. Для получения дополнительных сведений выполните в справке поиск по словам «режим песочницы».
Возвращает ссылку на объект, предоставляемый компонентом ActiveX.
Синтаксис
GetObject([имя_пути ] [, класс ] )
Функция GetObject имеет следующие аргументы:
|
Аргумент |
Описание |
|
|
Необязательный аргумент. Variant (String). Полный путь к файлу, содержащему объект, который требуется получить. Если аргумент имя_пути пропущен, класс является обязательным. |
|
|
Необязательный аргумент. Variant (String). Строка, представляющая класс объекта. |
Аргумент классаргумент использует синтаксис имя_приложения.тип_объекта и содержит следующие части:
|
Элемент |
Описание |
|
имя_приложения |
Обязательный аргумент. Variant (String). Имя приложения, предоставляющего объект. |
|
тип_объекта |
Обязательный аргумент. Variant (String). Тип или класс объекта, который требуется создать. |
Замечания
Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.
Функция GetObject используется для доступа к объекту ActiveX файла и его назначению объекту объектная переменная. Чтобы назначить объекту, возвращаемом объектом GetObject, объекту, возвращаемом объектом, используйте утверждение Set. Например:
Dim CADObject As Object
Set CADObject = GetObject("C:CADSCHEMA.CAD")
При выполнении этого кода приложение, связанное с указанным именем_пути, запускается, а объект в указанном файле активируется.
Если имя_пути содержит пустую строку («»), GetObject возвращает новый экземпляр объекта указанного типа. Если аргумент имя_пути пропущен, функция GetObject возвращает текущий активный объект указанного типа. Если такой объект не существует, возникает ошибка.
Некоторые приложения разрешают активировать часть файла. Добавьте в конец имени файла восклицательный знак (!), а после него строку, указывающую часть файла, которую требуется активировать. Сведения о создании этой строки см. в документации приложения, в котором был создан объект.
Например, в графическом редакторе может быть несколько уровней для рисунка, сохраненного в файле. Вы можете использовать следующий код для активации уровня рисунка с названием SCHEMA.CAD:
Set LayerObject = GetObject("C:CADSCHEMA.CAD!Layer3")
Если класс объекта не был задан, автоматизация определяет запускаемое приложение и активируемый объект на основе предоставленного имени файла. Некоторые файлы, однако, могут поддерживать несколько классов объектов. Например, рисунок может поддерживать три различных типа объектов — объект Application, объект Drawing и объект Toolbar, —каждый из которых является частью одного и того же файла. Чтобы указать, какой объект в файле требуется активировать, используйте необязательный аргумент класс. Например:
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 всегда возвращает один и тот же экземпляр, если он вызывается с нулевой строкой («»), и вызывает ошибку, если аргумент путь опущен. Получить ссылку на занятие, созданное с помощью Visual Basic, с помощью GetObject нельзя.
Пример
В этом примере функция GetObject применяется для получения ссылки на определенный лист Microsoft Office Excel 2007 (MyXL). Она использует свойство Application листа, чтобы сделать видимым Excel, закрыть его и т. п. Используя два вызова API, процедура DetectExcel Sub осуществляет поиск Excel и, если он выполняется, вводит его в текущую таблицу объектов. Первый вызов функции GetObject приводит к возникновению ошибки, если Microsoft Excel не выполняется. В этом примере ошибка приводит к заданию для флага ExcelWasNotRunning значения True. Второй вызов GetObject задает открытие файла. Если Excel еще не выполняется, второй вызов запускает его и возвращает ссылку на лист, представленный указанным файлом (mytest.xls). Файл должен существовать в указанном расположении; в противном случае генерируется ошибка автоматизации Visual Basic. Далее пример кода делает видимым и Excel, и окно, содержащее указанный лист. Наконец, если Excel не был изначально запущен, в коде используется метод Quit объекта Application для закрытия Excel. Если приложение уже выполнялось, попытка закрыть его не предпринимается. Сама ссылка освобождается посредством присвоения ей значения 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
Нужна дополнительная помощь?
- Remove From My Forums
-
Вопрос
-
-

0
The following code works fine on my Windows 10 64 computer, running Visual Basic 2013 and Excel 2010
Dim oExcel As Excel.Workbook = Nothing
oExcel = GetObject(path + filename)
oExcel.Application.Visible = True
oExcel.Windows(1).Visible = True
However, when I run the same code after having installed Office 2016, when the filename workbook is not opened, it opens two Excel windows, which are blank (no worksheets are displayed) and unresponsive. They have to be closed ending the task in Task
Manager.The code throws an error message saying index out of range, which is due to Windows.Count being 0.
I have added to my project the Microsoft Office 16 and Microsoft Excel 16 references, removing the Office 14 and Excel 16 previous references.
I reported this fault over a year ago and have avoided Office 2016 since in the hope that it would get fixed, as Microsoft told me they would. However, after installing Office 2016 again I see that the problem persits.
-
Any solution?
Many thanks.
-
| 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]
| 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]
|
mentos_has_arisen 0 / 0 / 0 Регистрация: 26.11.2009 Сообщений: 243 |
||||||||
|
1 |
||||||||
|
13.04.2011, 15:17. Показов 7012. Ответов 3 Метки нет (Все метки)
на 3-й строке выдает ошибку.. меняю строку на
выдает ошибку: Соль конечно не в этом.. GetObject посоветовали использовать для того, чтоб при обращении к Excel.Application не вбивать его в задачник.. ато сколько нажимаешь кнопку, столько и остается хвостов…
__________________
0 |
|
90 / 37 / 14 Регистрация: 03.11.2010 Сообщений: 429 |
|
|
13.04.2011, 19:17 |
2 |
|
Если в Excel’е открыть файл (например С:1.xls), а потом открыть файл с именем 1.xls, то появится сообщение — нельзя, такой файл уже есть.
0 |
|
Димит 90 / 37 / 14 Регистрация: 03.11.2010 Сообщений: 429 |
||||
|
13.04.2011, 21:32 |
3 |
|||
И ещё надо установить ссылку на библиотеку Microsoft Excel Object Library
0 |
|
Димит 90 / 37 / 14 Регистрация: 03.11.2010 Сообщений: 429 |
||||
|
13.04.2011, 21:35 |
4 |
|||
|
что-то не то загнал. Правильно:
Кстати, а как на этом форуме исправить своё сообщение?
0 |
|
ran Пользователь Сообщений: 7081 |
Приветствую! Windows(wbTmp.Name).Visible = True wbTmp.Close True Как сделать, чтобы и открывался нормально, и на экране не показывался? |
|
а чем мешает строка кода Windows(wbTmp.Name).Visible = True ??? PS: Сегодня впервые столкнулся с обычным файлом XLS, который GetObject не открыл |
|
|
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
Андрей, отключи обновление экрана и Я сам — дурнее всякого примера! … |
|
ran Пользователь Сообщений: 7081 |
Попробовал так |
|
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
Беда! Я сам — дурнее всякого примера! … |
|
ran Пользователь Сообщений: 7081 |
Спасибо,Сергей! |
|
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
А что непонятно? В момент GetObject все моргание и происходит Ты открываешь файл. А ты после него отключаешь обновтение. Поздно, батенька:-) Я сам — дурнее всякого примера! … |
|
ran Пользователь Сообщений: 7081 |
А непонятно следующее отключаем обновление Немного странно… |
|
Юрий М Модератор Сообщений: 60335 Контакты см. в профиле |
Ну ведь нелепо — отключать после того, как УЖЕ мигнуло 🙂 |
|
ran Пользователь Сообщений: 7081 |
{quote}{login=Юрий М}{date=13.10.2011 09:04}{thema=}{post}Ну ведь нелепо — отключать после того, как УЖЕ мигнуло :-){/post}{/quote} |
|
Юрий М Модератор Сообщений: 60335 Контакты см. в профиле |
🙂 Тогда другой пример: собираемся удалять лист, и не хотим, чтобы выскакивало предупреждение. СНАЧАЛА отключаем: |
|
nerv Пользователь Сообщений: 3071 |
Утром деньги, вечером стулья! |
|
ran Пользователь Сообщений: 7081 |
Неудачный пример и не работает, как надо. |
|
nerv Пользователь Сообщений: 3071 |
|
|
Юрий М Модератор Сообщений: 60335 Контакты см. в профиле |
{quote}{login=RAN}{date=13.10.2011 09:36}{thema=}{post}Неудачный пример…{/post}{/quote}Удачный — вот наглядная иллюстрация: |
|
ran Пользователь Сообщений: 7081 |
Вроде починил. |
|
nerv Пользователь Сообщений: 3071 |
думаю, что они будут работать по разному) Не обращай внимания, эт все мой «вечерний тупизм»))) |
|
слэн Пользователь Сообщений: 5192 |
#18 14.10.2011 10:04:22 а просто открыть экземпляр иксель createobject-ом потом workbook.open ? ничего не мигает.. Живи и дай жить.. |
I am getting an error:
«Run-Time error 91: Object Variable or With block variable not set» .
Debugging highlights the line with MsgBox():
Sub CATMain()
Dim xlApp As Excel.Application
Set xlApp = VBA.GetObject("", "Excel.Application")
Dim exlBook As Excel.Workbook
Set exlBook = xlApp.ActiveWorkbook
MsgBox exlBook.Name
End Sub
What could be wrong?
![]()
Vityata
42.1k8 gold badges55 silver badges94 bronze badges
asked Jul 23, 2018 at 14:10
Remove the "" from your code in VBA.GetObject() and it should work:
Sub TestMe()
Dim xlApp As Excel.Application
Set xlApp = VBA.GetObject(, "Excel.Application")
Dim exlBook As Excel.Workbook
Set exlBook = xlApp.ActiveWorkbook
MsgBox exlBook.Name
End Sub
MSDN GetObject. These are the parameters of GetObject():
-
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 theclass of the object.
answered Jul 23, 2018 at 14:29
![]()
VityataVityata
42.1k8 gold badges55 silver badges94 bronze badges
8
Add:
xlApp.Application.Visible = True
after set …
You’ll see why there’s no activeworkbook.name
Because of the «» you open a new instance
answered Jul 23, 2018 at 14:23
![]()
EvREvR
3,3482 gold badges12 silver badges23 bronze badges
1
In a CATIA vb module:
Sub CATMain()
Dim xlApp As Object
On Error Resume Next
Set xlApp = VBA.GetObject(, "Excel.Application")
On Error GoTo 0
If (xlApp Is Nothing) Then
MsgBox "Please start MS Excel prior running this script!!", vbCritical, "Excel not started"
Exit Sub
End If
Dim exlBook As Object
On Error Resume Next
Set exlBook = xlApp.ActiveWorkbook
On Error GoTo 0
If (exlBook Is Nothing) Then
MsgBox "No Workbook is openned", vbExclamation, "MS Excel is empty"
Exit Sub
End If
MsgBox exlBook.Name
End Sub
answered Jul 30, 2018 at 19:23
simpLE MAnsimpLE MAn
1,53413 silver badges22 bronze badges
- Remove From My Forums
-
Question
-
The below line causes the error:
set ExcelApp = GetObject(,»Excel.Application»)
Any suggestions on how to fix this? Thanks.
shazinus
Answers
-
You can’t do that with Excel.
That’s incorrect. The problem is that with VBScript from version 5.1 on the first argument in the GetObject() function needs to be an empty string. In earlier version, it needed to be a null argument (contrary to the documentation at the
time). My guess is that the OP found some old advice somewhere. If he just adds an empty string as the first argument, it will work as he expects — I know, I just tested it to be sure. That is, …set ExcelApp = GetObject("","Excel.Application") wsh.echo typename(excelapp)
Tom Lavedas
-
Edited by
Tuesday, November 29, 2011 2:23 PM
to fix a typo -
Proposed as answer by
Richard MuellerMVP
Tuesday, November 29, 2011 3:42 PM -
Marked as answer by
Richard MuellerMVP
Thursday, December 1, 2011 11:23 PM
-
Edited by
(((