Using excel microsoft office interop excel не работает

Proidoha

645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

1

12.04.2016, 16:17. Показов 10638. Ответов 19

Метки excel, imports, interop, vba (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго времени!

Имею на машине Вынь10, VB Express 2010 и 2016 офис.
Хочу прикрутить к программе пространство имен VBA Excel. И не получается. Внимательно прочитал вот это: https://msdn.microsoft.com/ru-… -snippet-1 , нашел вот эту запись, вставил, а оно мне говорит: «Пространство имен или тип, указанные в операторе Imports «Microsoft.Office.Interop», не содержат открытые члены или не могут быть найдены. Убедитесь, что пространство имен или тип определены и содержат хотя бы один открытый член. Убедитесь, что имя импортируемого элемента не было использовано в других Imports.»

VB.NET
1
Imports Microsoft.Office.Interop

Как правильно его прикрутить? Гугл мне не помог.



0



ViterAlex

8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

12.04.2016, 16:28

2

На сайте для кода VB ошибка, в версии для C# всё правильно. Должно быть:

VB.NET
1
Imports Excel = Microsoft.Office.Interop.Excel



0



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

12.04.2016, 16:53

 [ТС]

3

Пробовал. Та же ошибка. Мало того, я в ссылках на вкладке COM не могу найти Microsoft Excel Object Library. Это какая-то фишка 2016 версии, видимо.

Добавлено через 10 минут
http://stackoverflow.com/quest… erop-excel

Вот тут говорят, что надо импортировать Microsoft.Office 16.0 Object Library. Только оно не работает — пространство имен не появляется все равно.



0



8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

12.04.2016, 16:56

4

У меня стоит 2016. Всё присутствует. Сначал добавляешь ссылку на библиотеку, затем импортируешь пространство имён

Миниатюры

Imports Microsoft.Office.Interop не работает
 



1



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

12.04.2016, 17:35

 [ТС]

5

А у меня даже не предлагает interop после microsoft.office.

Я вот задумался: может быть причиной express-выпуск студии?

Миниатюры

Imports Microsoft.Office.Interop не работает
 



0



8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

12.04.2016, 17:54

6

Microsoft Excel 16.0 Object Library. Не Office



0



1083 / 819 / 145

Регистрация: 25.07.2015

Сообщений: 1,812

12.04.2016, 18:45

7

Что-то подсказывает , что VS2010 не коннектится с библиотеками 2016 офиса



0



8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

12.04.2016, 19:19

8

Это почему же?



0



Модератор

Эксперт .NET

3878 / 3200 / 482

Регистрация: 27.01.2014

Сообщений: 5,842

12.04.2016, 20:47

9

у меня все работает. вы не на вкладке COM ищите библиотеку а на вкладке NET.. и еще, смотрите на версию, не выбирайте версию 14.0 так как на машинах где стоит офис 2007-2014 ваша программа не запустится, выбирайте версию 12.0… это значит что начиная с офиса 2007 все последующие будут поддерживаться вашим ПО.



1



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

13.04.2016, 16:42

 [ТС]

10

У меня НЕТУ Microsoft Excel 16.0 Object Library ни на вкладке COM, ни на вкладке .NET. Могу скрины выложить.
Не могли бы Вы указать путь до нужной библиотеки? Поищу подобную у себя.

Что-то из области фантастики и сопряжения Win10, Office16 и VS2010.

Дома на Вынь7 и 2013 офисе с той же студией все ок — на вкладке .net есть microsoft.office.interop.excel 2 версий — 12 и 14.



0



Модератор

Эксперт .NET

3878 / 3200 / 482

Регистрация: 27.01.2014

Сообщений: 5,842

13.04.2016, 17:22

11

Лучший ответ Сообщение было отмечено Proidoha как решение

Решение

а тогда вопрос — а какой у вас офис? не 64 бит случайно?

посмотрите по этому пути:
C:Program Files (x86)Microsoft Visual Studio 10.0Visual Studio Tools for OfficePIAOffice12Microsoft.Office.lnterop.Excel .dll



2



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

13.04.2016, 18:12

 [ТС]

12

Цитата
Сообщение от Yury Komar
Посмотреть сообщение

а тогда вопрос — а какой у вас офис? не 64 бит случайно?
посмотрите по этому пути:
C:Program Files (x86)Microsoft Visual Studio 10.0Visual Studio Tools for OfficePIAOffice12Microsoft.Office.lnterop.Excel .dll

Да, Офис «стандартный 2016 х64».
В папке C:Program Files (x86)Microsoft Visual Studio 10.0 папки Visual Studio Tools for Office у меня нет. И это ответ на мой вопрос. Спасибо! Необходимо было установить этот пакет отдельно (он не входит в пакет VB 2010 Express по умолчанию).

Ссылка на требуемый пакет: https://www.microsoft.com/ru-r… x?id=48217



1



1706 / 1194 / 227

Регистрация: 23.12.2010

Сообщений: 1,526

14.04.2016, 07:15

13

хм… а как же без этих тулов цеплялись в vb6 или в версиях до 2005… Часом, когда ставили офис, не убрали в настройках галку, отвечающую за это? Что-то вроде «поддержка программирования» или как-то так… Я в свое время еще в 2003м офисе сэтим налажал. В итоге написанные уже программы с ним работать могли, а вот в новом проекте добавить ссылку никак нельзя было, и если открыть исходники других проектов — студия ругалась на эти ссылки. Позднее связывание при этом работает.



0



Модератор

Эксперт .NET

3878 / 3200 / 482

Регистрация: 27.01.2014

Сообщений: 5,842

14.04.2016, 08:49

14

vb6 не видел библиотек от 64-битного офиса. в NET с этим, суда по исходам данной темы, проблем нет… а в vb6 использовался COM объект, в NET же чаще люди используют вспомогательную библиотеку Office.Interop, которая является всего навсего набором констант и тому подобного… своего рода позднее связывание, но дающее помошь в редакторе кода с подсказками от Intellisense… кажется так



0



1706 / 1194 / 227

Регистрация: 23.12.2010

Сообщений: 1,526

14.04.2016, 09:11

15

Цитата
Сообщение от Yury Komar
Посмотреть сообщение

vb6 не видел библиотек от 64-битного офиса

не, я не в контексте х64. Просто комплекта VSTO ведь не было. Да и потом он уже появился только к 2005 версии, отдельным дистрибутом, а только с 2008й начал по умолчанию ставиться.
Я имел в виду, что при установке офиса вполне можно отключить возможность присоединения библ к среде программирования, и такое бывает в некоторых сборках 2003 по умолчанию (с чем я однажды и столкнулся). Проблема решилась переустановкой офиса в режиме исправления.
Как-то так…



0



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

14.04.2016, 13:01

 [ТС]

16

Цитата
Сообщение от Юпатов Дмитрий
Посмотреть сообщение

Часом, когда ставили офис, не убрали в настройках галку, отвечающую за это?

Сисадмины говорят, что никакие галочки не снимали.
Раньше написал, что проблема решена, но, к сожалению, это не так.
Установка Visual Studio Tools for Office вообще никак не изменила ситуацию:
Папка C:Program Files (x86)Microsoft Visual Studio 10.0Visual Studio Tools for Office по прежнему отсутствует
На диске C отсутствует файл Microsoft.Office.lnterop.Excel.dll

Нашел похожую тему на форуме: Как подключить microsoft.office.interop.excel
Предложенный в теме msi скачал и установил. И все равно никаких изменений.

Есть еще идеи как бороться с этой бедой?



0



Модератор

Эксперт .NET

3878 / 3200 / 482

Регистрация: 27.01.2014

Сообщений: 5,842

14.04.2016, 19:46

17

интересно получается. может все дело в Express версии студии? хотя врятли…



0



645 / 473 / 38

Регистрация: 04.11.2013

Сообщений: 1,949

15.04.2016, 15:22

 [ТС]

18

Решил беду скачав с домашнего компа полностью папку Visual Studio Tools for Office и подсунув программе нужную библиотеку вручную. Костыль, конечно, но хоть так. Пространство имен появилось, компиляцию пока не пробовал делать.



0



19 / 19 / 0

Регистрация: 05.02.2015

Сообщений: 175

08.09.2016, 16:59

19

Доброго вечера.
Подскажите, как сделать «универсальную ссылку», к примеру на excel, если заранее не известно, какой офис установлен на ПК?



0



Модератор

Эксперт .NET

3878 / 3200 / 482

Регистрация: 27.01.2014

Сообщений: 5,842

08.09.2016, 17:28

20

Devils, универсальных не бывает, есть только позднее связывание, в котором все рабочие объекты имеют тип Object вместо Excel, Word, Range и так далее.



0



I have a Windows Form Application in VS2012 C# and I’m trying to use Microsoft.Office.Interop.Excel; in order to make an Excel spreadsheet. Whenever I try to type some code such as

Application _excelApp;

or

var application = new Application();

I keep getting the same error which is «Application is an ambiguous reference between ‘System.Windows.Form.Application’ and ‘Microsoft.Office.Inter.Excel.Application’. I was just wondering what the solution is so I could start using the Interop.Excel. Any help would be greatly appreciated.

asked Jun 5, 2013 at 19:36

Stock's user avatar

StockStock

773 silver badges15 bronze badges

0

Either use the fully-qualified type name (including namespaces) or use a namespace alias.

using Excel = Microsoft.Office.Interop.Excel; // In your usings

var application = new Excel.Application();

or

var application = new Microsoft.Office.Interop.Excel.Application();

answered Jun 5, 2013 at 19:38

wgraham's user avatar

wgrahamwgraham

1,38311 silver badges16 bronze badges

  • Remove From My Forums
  • Question

  • I am trying to use this namespace and downloaded the O2003pia.exe from http://support.microsoft.com/kb/897646.

    I ran the msi and see the Interop files in the GAC but when I try to ‘Add a Reference’ in VS2005, I do not see any of the Interop namespaces.

    I already had Office 2003 installed before I ran the above msi.

    What else am I doing wrong. Why aren’t these included with VS2005 in the first place…………..

    Please help,

    JJM

Answers

  • Hi JJJMonty,

    Actually, if you want to use this DLL, following these steps:

    1.       On the Project menu, click Add Reference.

    2.       On the COM tab, locate Microsoft Excel Object Library, and then click Select. In Visual Studio 2005, locate Microsoft Excel 11.0 Object Library on the COM tab.

    3.       Click OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click “Yes”.

    Then you should be able to use this interop DLL, for more details, please visit Primary Interop Assemblies.

    Hope this helps!

    Thanks!

I am having troubles adding the excel reference to my project. I have already installed Primary Interop Assemblies.

The project is detecting the Microsoft.Office.Interop.Word assembly reference correctly but the excel reference still cannot be found.

When I try to manually add the reference, I right click the project, add reference, navigate to the Microsoft.Office.Interop.Excel file and try to add it manually. Once i select the reference I then make sure the reference is checked, then hit ok. Nothing happens, it fails to actually add the reference path to the project.

Using VS2012 Ultimate.

Any suggestions on what I can do to get the project to see the excel reference?

41686d6564 stands w. Palestine's user avatar

asked Oct 23, 2013 at 13:38

stylex's user avatar

6

If you don’t have excel installed, run this command in the nuget-packet-manager-console:

Install-Package Microsoft.Office.Interop.Excel

answered Apr 14, 2017 at 14:51

Luca Ziegler's user avatar

Luca ZieglerLuca Ziegler

3,0981 gold badge22 silver badges39 bronze badges

I installed Microsoft office PIAs, but I had the same problem, cannot find microsoft.office.interop.excel dll, I also I installed Visual Studio 2010 Tools for the Office System 4.0 Runtime Service Pack 1 but still the problem persist.

Finally I resolve the problem with an add of Office / SharePoint development package to my Visual Studio 2017 installation:

Go to Tools > Get Tools and Features ..

And then check Office / sharepoint development and modify your installation.

answered Apr 4, 2018 at 15:03

Mohammed EL KALAKHI's user avatar

1

I installed MS Office 13 and from then on I started getting this error in VS 2012 project.
I tried adding the MS Office lib via COM control but that didnt work.
Finally I had to add this library references from the «Extensions» section (not not under COM); had to select Microsoft.Office.Interop.Excel, version 15.0.0.0. That fixed the error.

Hope that helps some.

answered Apr 11, 2016 at 19:16

Yoda's user avatar

Hello,

I am new to VB and have been trying to create a small app using excel. I went to the Microsoft support page and followed the instructions to add a reference to Excel 15.0 that is installed on my computer and then insert at the top of my Form1 the following «Imports Excel = Microsoft.Office.Interop.Excel» and the «Excel = Microsoft.Office.Interop.Excel» portion is underlined by the editor with no recommended solution. Do I need to upgrade my Visual Studio 2013 or install any add-ons? Any advice is greatly appreciated!

Here is the error I get when attempting to run the code

Warning	1	Namespace or type specified in the Imports 'Microsoft.Office.Interop.Excel' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. C:UsersPhilipDocumentsVisual Studio 2013ProjectsExcel projectsVBdotNetSetup 5-26-17VBdotNetSetup 5-26-17Form1.vb	4	9	VBdotNetSetup 5-26-17

What I have tried:

I have tried searching the Microsoft support pages and have had no luck.

Comments


1 solution

Solution 3

If you go to:

Visual Studio -> Main Menu -> Project -> Add Reference

Choose to see the COM objects, and if you have Microsoft Office installed, you should be able to scroll down to:

Microsoft Excel [xx.x] object library

After that, your IMPORTS declaration should work.

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Понравилась статья? Поделить с друзьями:
  • Using excel microsoft office interop excel как подключить
  • Using excel in programming
  • Using excel if function in vba
  • Using excel for personal accounting
  • Using excel for functions