Dim app as word application ошибка
Репутация: нет
Всего: нет
Необходимо, при нажатии на кнопку передать все записи (по условию фильтра) из Access в Word по готовому шаблону /dot/шаблон.dot при этом сколько записей столько и страниц в документе.
Написал в VBA следующий код, отталкиваясь от примера в Интернете.
Код |
Function funOutputWord(strPathDot As String) As Boolean Dim app As Object |
Set app = CreateObject("Word.Application")
app.Visible = True
app.Documents.Add strPathDot
With app.ActiveDocument
.Bookmarks.Item("ФИО").Range.Text = Nz(Me.ФИО)
.Bookmarks.Item("Улица").Range.Text = Nz(Me.Улица)
.Bookmarks.Item("Дом").Range.Text = Nz(Me.Дом)
.Bookmarks.Item("Квартира").Range.Text = Nz(Me.Квартира)
End With
Код |
Dim strPathDot As String strPathDot = CurrentProject.Path & "\dot\шаблон.dot" Call funOutputWord(strPathDot) |
Репутация: 21
Всего: 21
Репутация: нет
Всего: нет
Цитата(bopoha @ 17.8.2010, 21:56 ) |
А где цикл по записям? |
Точно! А слона я и не увидел!
После правки выдает ошибку 5941 "Запрашиваемый номер семейства не существует"
Код |
Function funOutputWord(strPathDot As String) As Boolean Dim app As Object |
Set app = CreateObject("Word.Application")
app.Visible = True
app.Documents.Add strPathDot
Репутация: 21
Всего: 21
Artmishin, а переходить по записям кто будет?
Лучше делать так:
Код |
dim rst as DAO.Recordset |
set rst = me.recordsetclone
'-- rst.bookmark = me.bookmark '-- если нужно начать с текущей записи
Репутация: нет
Всего: нет
Код |
Public Sub otUved5000() |
'Код для Word
Dim pstrAppPath As String
Dim objWord5000 As Word.Application
On Error Resume Next
Set objWord5000 = GetObject(, "Word.Application")
If objWord5000 Is Nothing Then
Set objWord5000 = New Word.Application
If objWord5000 Is Nothing Then
MsgBox "MS Word не установлен на Вашем компьютере!"
End If
End If
objWord5000.Documents.Add (pstrAppPath & "\Dot\Шаблон.dot")
objWord5000.ActiveDocument.MailMerge.MainDocumentType = wdFormLetters
objWord5000.ActiveDocument.MailMerge.OpenDataSource Name:= _
pstrAppPath & "\DB.mdb", ConfirmConversions:=False, _
ReadOnly:=True, LinkToSource:=True, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
Connection:="QUERY Main_group", SQLStatement:= _
"SELECT * FROM Main_group WHERE Активация = True", SQLStatement1:=""
With objWord5000.ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.Execute
End With
Добавлено через 7 минут и 14 секунд
Теперь проблема в следующем, имеется таблица с двумя логическими полями "Поле1" и "Поле2". Выбор необходимых записей происходит по условию Поле1 = True. Необходимо после выполнения слияния с Word, сначала приравнять значения этих полей, а затем очистить Поле1. Написал код, но никак не пойму куда влепить условие отбора?
Код |
Dim rst5000 As Recordset Dim dbs5000 As Database |
Set dbs5000 = OpenDatabase("DB.mdb")
Set rst5000 = dbs5000.OpenRecordset("Main_group", dbOpenForwardOnly)
Do While Not rst5000.EOF
Me.Поле2 = Me.Поле1
Me.Поле1 = False
Эта статья содержит советы по устранению неполадок для диагностики и устранения неполадок, вызывающих возникновение этой ошибки.
Дополнительные сведения
В отличие от некоторых ошибок в Visual Basic нет не одной из причин об ошибке 429. Проблема возникает из-за ошибки в конфигурации системы или приложения или компонента отсутствует или поврежден. Поиск точная причина заключается в возможности устранения. При возникновении этой ошибки на клиентском компьютере, существует ряд вещей, которые необходимо проверить для выявления и устранения ошибки.
Позже, элементы предоставляют некоторые практические советы по устранению данной ошибки при работе с приложениями Office. Часть этой информации также относится к серверам Microsoft Office COM также, но в данной статье предполагается, что вы пытаетесь автоматизации Microsoft Office.
Проверка кода
Первое место, чтобы начать поиск проблемы — в коде. До устранения ошибки, необходимо знать, где произошла ошибка. Попробуйте сузить до одной строки кода.
Найдя код, который не удается, попробуйте сделать следующее:
Убедитесь, что в коде используется явное создание объекта. Любые проблемы проще найти и определить, если проблема сведена до отдельного действия. Например не выполните следующее:
Оба эти метода используется неявное создание объекта. Microsoft Word не начинается, пока переменная называется по крайней мере один раз. Поскольку переменная может вызываться в разных частях программы, это может сделать проблему трудно локализовать. Кроме того неясно, связана ли проблема с созданием объекта приложения или объекта документа.
Вместо этого указать явные вызовы для создания каждого объекта в отдельности:
Это упрощает выявление проблемы и делает код более удобным для чтения.
При создании экземпляра приложения Microsoft Office, используйте вместо New CreateObject . CreateObject более точно соответствует процесс создания, используемый большинство клиентов Visual C++ и позволяет возможные изменения CLSID сервера между версиями. Функция CreateObject можно использовать с объектами с ранним связыванием и поздним связыванием.
Проверьте правильность строки ProgID, передаваемые CreateObject , а также является независимость от версии (то есть использовать «Excel.Application» вместо «Excel.Application.8»). Возможно, что система, которую дает сбой имеет более старой или новой версии Microsoft Office до версии, указанной в идентификатор ProgID.
Для упрощения отладки приложений, которые не запускаются в Интегрированной среде разработки, команда Erl сообщить номер строки, который не проходит. Например следующий код сообщит, какой объект автоматизации невозможно (Word или Excel):
При автоматизации из ASP или компонента MTS используйте CreateObject вместо Server.CreateObject(). Используя Server.CreateObject будет создан экземпляр приложения Office с использованием идентификатора пакета MTS, который приводит к проблемам с Microsoft Office.
Проверка сервера автоматизации
Самые распространенные причины возникновения ошибки CreateObject или New , проблем с самим приложением сервера. Как правило эти проблемы являются конфигурации или установки приложения. Ниже приведены некоторые элементы для проверки.
Проверьте Microsoft Office, приложение, которое требуется автоматизация установлена на локальном компьютере и убедитесь в том, что можно запустить приложение с самого начала и запустить диалоговое окно. Если программа не может быть запущена вручную, он не будет работать через автоматизацию.
Известны проблемы возникает при автоматизации Word или Excel, если шаблон Normal.dot (Word) или файл ресурсов Excel.xlb (Excel), был поврежден. Чтобы проверить, если произошло повреждение, поиск локальных жестких дисков для поиска всех экземпляров Normal.dot или *.xlb. (Обратите внимание, что при запуске Windows 2000, Windows NT или Windows 95 или Windows 98 с включенными профилями, может оказаться несколько копий этих файлов для каждого профиля пользователя в системе.) Временно переименуйте файлы Normal.dot или файлы *.xlb и повторно запустите проверку автоматизации (Word и Excel создаст эти файлы, если они не может их найти). Код теперь работать? Если Да, выберите файлы, которые вы переименовали следует удалить, так как они повреждены. Если это не так, переименуйте их обратно в их исходные имена, будут потеряны все пользовательские параметры, сохраненные в этих файлах.
При работе в Windows NT, Windows 2000, Windows XP или Windows Server 2003 система, запустите приложения под учетной записью администратора. Серверов Office требуется доступ на чтение и запись в реестре и на диске и могут не загружаться должным образом, если ваши текущие параметры безопасности запрещают эту привилегию.
Проверка системы
Конфигурация системы также может вызвать проблемы с созданием out-of-process COM-серверов. Ниже приведены несколько советов по проверке систем место возникновения ошибки.
Проблема происходит с любым сервером out-of-process? Если у вас есть приложение, которое использует только определенный COM-сервер (например, Word), вы захотите проверить на другой сервер out-of-process, чтобы убедиться, что проблема не связана с COM сам слой. Если нет out-of-process COM-сервера могут быть созданы в этой системе, переустановке системы OLE файлов (см. ниже), или для устранения этой проблемы потребуется переустановка операционной системы.
Проверьте номера версий системных файлов OLE, которые управляют автоматизацией. Эти файлы обычно устанавливаются как набор и должно соответствовать номера построений. Неправильно настроенная программа установки может ошибочно установить файлы по отдельности, к ним становятся несоответствие. Чтобы избежать проблем при автоматизации, следует проверять файлы, убедитесь, что файлы совпадают построений.
Файлы автоматизации можно найти в каталоге Windows\System или Winnt\System32. Ниже приведен список файлов для проверки:
+---------------+-------------+----------------+
| File Name | Version | Date Modified |
+---------------+-------------+----------------+
| Asycfilt.dll | 2.40.4275 | March 08, 1999 |
| Oleaut32.dll | 2.40.4275 | March 08, 1999 |
| Olepro32.dll | 5.0.4275 | March 08, 1999 |
| Stdole2.tlb | 2.40.4275 | March 08, 1999 |
+---------------+-------------+----------------+
Проверьте версию файла, щелкните правой кнопкой мыши файл в обозревателе и при выборе свойства из всплывающего меню. Наиболее важные значения, последние четыре цифры в версии файла (номер сборки) и дату последнего изменения. Необходимо убедиться, что эти значения одинаковы для всех файлов автоматизации.
Обратите внимание, что номера версии и даты, приведенном выше, например исключительно в целях. Значения могут отличаться. Важно, что эти значения соответствуют друг другу, а не в этой таблице.
Если файлы не соответствуют номера сборок или даты изменений, вы можете загрузить самораспаковывающийся программа обновит файлы автоматизации. Для получения дополнительных сведений щелкните следующий номер статьи базы знаний Майкрософт:
290887 VBRun60sp6.exe устанавливает файлы времени выполнения Visual Basic 6.0 SP6
Windows NT 4.0 имеет известные проблемы с запуском серверы автоматизации, которые находятся в папке, которая содержит пробелы в имени и напоминает другую папку, совпадают с первыми 8 символами. Например сервер, живущих в C:\Program Files\SomeFolder может не запуститься во время вызова к CreateObject, если система называется C:\Program Stuff\SomeFolder другую папку. Дополнительные сведения см в следующей статье базы знаний:Дополнительные сведения об этой проблеме и действия, чтобы избежать этого, щелкните следующий номер статьи базы знаний Майкрософт:
Ошибка 185126 : COM и OLE-сервер не запускается в Windows NT 4.0
Переустановка Microsoft Office.
Если ни один из предыдущих шагов позволяет устранить проблему, рассмотрите возможность удаления и переустановки Microsoft Office. Корпорация Майкрософт рекомендует сначала удалить существующую версию, а затем переустановите с исходных установочных дисков.
Полный список удаляемых элементов можно найти в следующих статьях базы знаний:
219423 OFF2000: как полностью удалить Microsoft Office 2000
158658 OFF97: как полностью удалить Microsoft Office 97
Ссылки
240377 HOWTO: Убедитесь в правильности установки Jet 3.5 (часть I)
Последние сведения и примеры кода по автоматизации Microsoft Office можно найти на сайте поддержки Microsoft Online по:
When you use the New operator or the CreateObject function in Microsoft Visual Basic to create an instance of a Microsoft Office application, you may receive the following error message:
Run-time error '429': ActiveX component can't create object
This error occurs when the Component Object Model (COM) cannot create the requested Automation object, and the Automation object is, therefore, unavailable to Visual Basic. This error does not occur on all computers.
This article describes how to diagnose and resolve common problems that may cause this error.
More Information
In Visual Basic, there are several causes of error 429. The error occurs if any of the following conditions is true:
There is a mistake in the application.
There is a mistake in the system configuration.
There is a missing component.
There is a damaged component.
To find the cause of the error, isolate the problem. If you receive the "429" error message on a client computer, use the following information to isolate and resolve the error in Microsoft Office applications.
Note Some of the following information may also apply to non-Office COM servers. However, this article assumes that you want to automate Office applications.
Examine the code
Before you troubleshoot the error, try to isolate a single line of code that may be causing the problem.
If you discover that a single line of code may be causing the problem, complete these procedures:
Make sure that the code uses explicit object creation.
Problems are easier to identify if they are narrowed down to a single action. For example, look for implicit object creation that's used as one of the following.
Both of these code samples use implicit object creation. Microsoft Office Word 2003 does not start until the variable is called at least one time. Because the variable may be called in different parts of the program, the problem may be difficult to locate. It may be difficult to verify that the problem is caused when the Application object is created or when the Document object is created.
Instead, you can make explicit calls to create each object separately, as follows.
When you make explicit calls to create each object separately, the problem is easier to isolate. This may also make the code easier to read.
Use the CreateObject function instead of the New operator when you create an instance of an Office application.
The CreateObject function closely maps the creation process that most Microsoft Visual C++ clients use. The CreateObject function also permits changes in the CLSID of the server between versions. You can use the CreateObject function with early-bound objects and with late-bound objects.
Verify that the "ProgID" string that is passed to
CreateObject is correct, and then verify that the "ProgID" string is version independent. For example, use the "Excel.Application" string instead of using the "Excel.Application.8" string. The system that fails may have an older version of Microsoft Office or a newer version of Microsoft Office than the version that you specified in the "ProgID" string.
Use the Erl command to report the line number of the line of code that does not succeed. This may help you debug applications that cannot run in the IDE. The following code tells you which Automation object cannot be created (Microsoft Word or Microsoft Office Excel 2003):
Use the MsgBox function and the line number to track the error.
Use late-binding as follows:
Early-bound objects require their custom interfaces to be marshaled across process boundaries. If the custom interface cannot be marshaled during CreateObject or during New, you receive the "429" error message. A late-bound object uses the IDispatch system-defined interface that does not require a custom proxy to be marshaled. Use a late-bound object to verify that this procedure works correctly.
If the problem occurs only when the object is early-bound, the problem is in the server application. Typically, you can reinstall the application as described in the "Examine the Automation Server" section of this article to correct the problem.
Examine the automation server
The most common reason for an error to occur when you use CreateObject or New is a problem that affects the server application. Typically, the configuration of the application or the setup of the application causes the problem. To troubleshoot, use following methods:
Verify that the Office application that you want to automate is installed on the local computer. Make sure that you can run the application. To do this, click Start, click
Run, and then try to run the application. If you cannot run the application manually, the application will not work through automation.
Re-register the application as follows:
Click Start, and then click Run.
In the Run dialog box, type the path of the server, and then append /RegServer to the end of the line.
The application runs silently. The application is re-registered as a COM server.
If the problem occurs because a registry key is missing, these steps typically correct the problem.
Examine the LocalServer32 key under the CLSID for the application that you want to automate. Make sure that the LocalServer32 key points to the correct location for the application. Make sure that the path name is in a short path (DOS 8.3) format. You do not have to register a server by using a short path name. However, long path names that include embedded spaces may cause problems on some systems.
To examine the path key that is stored for the server, start the Windows Registry Editor, as follows:
Click Start, and then click Run.
Type regedit, and then click OK.
Move to the HKEY_CLASSES_ROOT\CLSID key.
The CLSIDs for the registered automation servers on the system are under this key.
Use the following values of the CLSID key to find the key that represents the Office application that you want to automate. Examine the LocalServer32 key of the CLSID key for the path.
Check the path to make sure that it matches the actual location of the file.
Note Short path names may seem correct when they are not correct. For example, both Office and Microsoft Internet Explorer (if they are installed in their default locations) have a short path that is similar to C:\PROGRA~1\MICROS~X\ (where
X is a number). This name may not initially appear to be a short path name.
To determine whether the path is correct, follow these steps:
Click Start, and then click Run.
Copy the value from the registry, and then paste the value in the Run dialog box.
Note Remove the /automation switch before you run the application.
Verify that the application runs correctly.
If the application runs after you click OK, the server is registered correctly. If the application does not run after you click OK, replace the value of the LocalServer32 key with the correct path. Use a short path name if you can.
Test for possible corruption of the Normal.dot template or of the Excel.xlb resource file. Problems may occur when you automate Microsoft Word or Microsoft Excel if either the Normal.dot template in Word or the Excel.xlb resource file in Excel is corrupted. To test these files, search the local hard disks for all instances of Normal.dot or of Excel.xlb.
Note You may find multiple copies of these files. There is one copy of each of these files for each user profile that is installed on the system.
Temporarily rename the Normal.dot files or the Excel.xlb files, and then rerun your automation test. Word and Excel both create these files if they cannot find them. Verify that the code works. If the code works when a new Normal.dot file is created, delete the files that you renamed. These files are corrupted. If the code does not work, you must revert these files to their original file names to save any custom settings that are saved in these files.
Run the application under the Administrator account. Office servers require Read/Write access to the registry and to the disk drive. Office servers may not load correctly if your current security settings deny Read/Write access.
Examine the system
System configuration may also cause problems for the creation of out-of-process COM servers. To troubleshoot, use the following methods on the system on which the error occurs:
Determine whether the problem occurs with any out-of-process server. If you have an application that uses a particular COM server (such as Word), test a different out-of-process server to make sure that the problem is not occuring in the COM layer itself. If you cannot create an out-of-process COM server on the computer, reinstall the OLE system files as described in the "Reinstalling Microsoft Office" section of this article, or reinstall the operating system to resolve the problem.
Examine the version numbers for the OLE system files that manage automation. These files are typically installed as a set. These files must match build numbers. An incorrectly configured setup utility can mistakenly install the files separately. This causes the files to be mismatched. To avoid problems in automation, examine the files to make sure that the files builds are matched.
The automation files are located in the Windows\System32 directory. Examine the following files.
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I had read the referenced similar questions and answers, especially I tried the answer to "Opening MS Word 2010 (Office 14) in Visual Basic" but it does not work with me.
I have a Win 2008R2 Server (64bit) with Word 2010 (Office Standard, 32 bit) and VS 2010 (working with remote access)
Private Function oeffneUrlInWord(ByVal url As String) As Microsoft.Office.Interop.Word.Document
Dim AppWord = New Microsoft.Office.Interop.Word.Application
Dim wordDocument As Microsoft.Office.Interop.Word.Document = AppWord.Documents.Open("D:\tmp\STARS_TEST.doc")
wordDocument.Activate()
Return wordDocument
End Function
The referenced Microsoft.Office.Interop.Word has Version 14.0.4733.1000
At the test phase the return value is not accessed any more - later the Window should be positioned and closed from Application (and the file URL will be delivered - I changed the call to bare essentials to find the problem - without success).
As a Result "WINWORD.EXE" Process will be found in Process List of Tas Manager (also Version 14.0. ) and the file is blocked by the word handle, but the window will not be shown. It also das not appear in Application-Tab of Task-Manager.
Up to now (word 12 with Win XP) we got around by open it via a navigate2 command to the controled Browser (which still runs on 2008R2), but with this I get no control on the Window to resize and close it from the parent program. It seems the process cannot connect to the desktop of Windows, but I have tested a lot - I do not have an idea, why?
Репутация: нет
Всего: нет
Код |
Dim WordApp As Word.Application Dim WordDoc As Word.Document |
Private Sub Form_Load()
Set WordApp = New Word.Application
Set WordDoc = Word.Application.Documents.Open("C:\1.doc")
Set WordApp = Nothing
Set WordDoc = Nothing
Set WordApp = New Word.Application
Set WordDoc = Word.Application.Documents.Open("C:\1.doc") '1
На строке "'1" возникает ошибка № 462 ("The remote server machine does not exist or is unavailable")
Вроде бы и открываю правильно и закрываю, перед открытием файла приложение открываю, а все равно ошибка.
Как её устранить?
Репутация: 34
Всего: 453
О(б)суждение моих действий - в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция - Администрация форума.
Репутация: нет
Всего: нет
Репутация: 34
Всего: 453
А зачем Вы создаете объект Word.Application, который не используете?
Что до вероятного источника ошибки - например просто не успевает сняться блокировка, вызванная первым доступом к файлу.
О(б)суждение моих действий - в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция - Администрация форума.
Репутация: нет
Всего: нет
Word.Application - да тут я сфальшивил имелось в виду WordApp.Documents.
Цитата |
Что до вероятного источника ошибки - например просто не успевает сняться блокировка, вызванная первым доступом к файлу. |
Скорее всего нет, ведь приведенный мною код упращенный, и между 12 и 14 строками не пустая строка а целые процедуры
Репутация: нет
Всего: нет
Отлично! Понял в чем дело!
Вот так все работает:
Код |
Dim WordApp As Word.Application Dim WordDoc As Word.Document |
Private Sub Form_Load()
Set WordApp = New Word.Application
Set WordDoc = WordApp.Documents.Open("C:\1.doc") ' Word.Application ->WordApp
Set WordApp = Nothing
Set WordDoc = Nothing
Set WordApp = New Word.Application
Set WordDoc = WordApp.Documents.Open("C:\1.doc") ' Word.Application ->WordApp
Set WordApp = Nothing
Set WordDoc = Nothing
End Sub
Спасибо за помощь.
Запрещается!
1. Публиковать ссылки на вскрытые компоненты
2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
- Литературу по VB обсуждаем здесь
- Действия модераторов можно обсудить здесь
- С просьбами о написании курсовой, реферата и т.п. обращаться сюда
- Вопросы по реализации алгоритмов рассматриваются здесь
- Используйте теги [code=vb][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.
- FAQ раздела лежит здесь!
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Akina.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) | |
0 Пользователей: | |
« Предыдущая тема | VB6 | Следующая тема » |
[ Время генерации скрипта: 0.1117 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Читайте также: