Ошибка runtime error 5941

При попытке использовать Microsoft Visual Basic for Applications (VBA) для изменения свойств документа появляется одно из приведенных ниже сообщений об ошибке.

Проблема

При попытке использовать Microsoft Visual Basic for Applications (VBA) для изменения свойств документа появляется одно из приведенных ниже сообщений об ошибке.

Ошибка при выполнении ‘4248’:

Команда недоступна, так как нет открытых документов

Ошибка при выполнении ‘4605’:
Метод или свойство недоступны, поскольку окно документа не активно

или

Ошибка при выполнении ‘5941’:
Запрашиваемый номер семейства не существует

Причина

Проблема возникает, когда нет открытых документов или не открыт документ, на который сделана ссылка. В программе Word предусмотрено изменение свойств только открытых документов.

Примечание. Такие сообщения об ошибках могут появиться также в том случае, если открыт документ, у которого свойство Видимый имеет значение Ложь.

Временное решение

Корпорация Microsoft предлагает примеры программного кода только для иллюстрации и не предоставляет явных или подразумеваемых гарантий относительно их корректной работы в конкретных случаях и в пользовательских приложениях. Примеры в данной статье рассчитаны на пользователя, имеющего достаточный уровень знаний соответствующего языка программирования, а также необходимых средств разработки и отладки. Специалисты служб технической поддержки Microsoft могут пояснить назначение тех или иных конструкций кода в конкретном примере, но модификация примеров и их адаптация к задачам разработчика не поддерживается. Если вам требуется дополнительная консультация по вопросам программирования, вы можете обратиться в службу консалтинга Microsoft или связаться с сертифицированными партнерами компании Microsoft. Дополнительную информацию о партнерах корпорации Microsoft можно найти в Интернете по следующему адресу:

http://www.microsoft.com/partner/referral/ За дополнительной информацией обратитесь к веб-узле корпорации Microsoft по адресу:

http://support.microsoft.com/default.aspx?scid=fh;RU;CNTACTMSЗа дополнительной информацией об использовании приведенных в этой статье примеров обратитесь к следующей статье Microsoft Knowledge Base:

290140 How to Run Sample Code from Knowledge Ниже приведен пример макроса на языке Visual Basic for Applications для изменения значения поля Заголовок в диалоговом окне Свойства. Пример содержит специальный программный код для перехвата ошибок на случай, если нет открытых документов, и вывода соответствующего сообщения.

Sub ChangeDocProperties()

On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit Sub

ErrHandler:
If Err <> 0 Then
'
' Display an error message.
'
MsgBox Err.Description
'
' Clear the error.
'
Err.Clear
Resume Next

End If

End Sub

Приведенный ниже программный код предусмотрен для выполнения следующих целей.

  • Перехват ошибок, если нет открытых документов

    и

  • Создание нового документа при перехвате ошибки

    и

  • Возобновление нормальной работы в строке, вызвавшей появление ошибки

Sub ChangeDocProperties()

On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit Sub

ErrHandler:
If Err <> 0 Then
'
' Add a document.
'
Documents.Add
'
' Clear the error.
'
Err.Clear
'
' Run the code that caused the error.
'
Resume

End If

End Sub

Ссылки

Для получения помощи по работе с Visual Basic обратитесь к следующей статье Microsoft Knowledge Base:

305326 Programming Resources for Visual Basic for Applications

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

Icon Ex Номер ошибки: Ошибка 5941
Название ошибки: Microsoft Word Error 5941
Описание ошибки: Ошибка 5941: Возникла ошибка в приложении Microsoft Word. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Word
Относится к: Windows XP, Vista, 7, 8, 10, 11

Сводка «Microsoft Word Error 5941

Это наиболее распространенное условие «Microsoft Word Error 5941», известное как ошибка времени выполнения (ошибка). Программисты работают через различные уровни отладки, пытаясь убедиться, что Microsoft Word как можно ближе к безошибочным. Ошибки, такие как ошибка 5941, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

В выпуске последней версии Microsoft Word может возникнуть ошибка, которая гласит: «Microsoft Word Error 5941». Сообщение об этой ошибке 5941 позволит разработчикам обновить свое приложение и исправить любые ошибки, которые могут вызвать его. Затем Microsoft Corporation будет иметь знания, чтобы исследовать, как и где устранить проблему. Таким образом, в этих случаях разработчик выпустит обновление программы Microsoft Word, чтобы исправить отображаемое сообщение об ошибке (и другие сообщенные проблемы).

Что вызывает ошибку 5941 во время выполнения?

Сбой устройства или Microsoft Word обычно может проявляться с «Microsoft Word Error 5941» в качестве проблемы во время выполнения. Причины сбоев обработки можно отличить, классифицируя ошибки 5941 следующим образом:.

Ошибка 5941 Crash — Ошибка 5941 является хорошо известной, которая происходит, когда неправильная строка кода компилируется в исходный код программы. Это возникает, когда Microsoft Word не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.

Утечка памяти «Microsoft Word Error 5941» — при утечке памяти Microsoft Word это может привести к медленной работе устройства из-за нехватки системных ресурсов. Потенциальные триггеры могут быть бесконечным циклом, что приводит к тому, что работа программы запускается снова и снова.

Ошибка 5941 Logic Error — «логическая ошибка», как говорят, генерируется, когда программное обеспечение получает правильный ввод, но генерирует неверный вывод. Обычные причины этой проблемы связаны с ошибками в обработке данных.

Большинство ошибок Microsoft Word Error 5941 являются результатом отсутствия или повреждения версии файла, установленного Microsoft Word. Возникновение подобных проблем является раздражающим фактором, однако их легко устранить, заменив файл Microsoft Corporation, из-за которого возникает проблема. В некоторых случаях реестр Windows пытается загрузить файл Microsoft Word Error 5941, который больше не существует; в таких ситуациях рекомендуется запустить сканирование реестра, чтобы исправить любые недопустимые ссылки на пути к файлам.

Распространенные сообщения об ошибках в Microsoft Word Error 5941

Частичный список ошибок Microsoft Word Error 5941 Microsoft Word:

  • «Ошибка в приложении: Microsoft Word Error 5941»
  • «Microsoft Word Error 5941 не является приложением Win32.»
  • «Microsoft Word Error 5941 должен быть закрыт. «
  • «К сожалению, мы не можем найти Microsoft Word Error 5941. «
  • «Microsoft Word Error 5941 не найден.»
  • «Проблема при запуске приложения: Microsoft Word Error 5941. «
  • «Файл Microsoft Word Error 5941 не запущен.»
  • «Microsoft Word Error 5941 выйти. «
  • «Ошибка пути программного обеспечения: Microsoft Word Error 5941. «

Проблемы Microsoft Word Microsoft Word Error 5941 возникают при установке, во время работы программного обеспечения, связанного с Microsoft Word Error 5941, во время завершения работы или запуска или менее вероятно во время обновления операционной системы. При появлении ошибки Microsoft Word Error 5941 запишите вхождения для устранения неполадок Microsoft Word и чтобы HelpMicrosoft Corporation найти причину.

Microsoft Word Error 5941 Истоки проблем

Проблемы Microsoft Word Error 5941 вызваны поврежденным или отсутствующим Microsoft Word Error 5941, недопустимыми ключами реестра, связанными с Microsoft Word, или вредоносным ПО.

В первую очередь, проблемы Microsoft Word Error 5941 создаются:

  • Недопустимая или поврежденная запись Microsoft Word Error 5941.
  • Файл Microsoft Word Error 5941 поврежден от вирусной инфекции.
  • Microsoft Word Error 5941 злонамеренно или ошибочно удален другим программным обеспечением (кроме Microsoft Word).
  • Microsoft Word Error 5941 конфликтует с другой программой (общим файлом).
  • Поврежденная установка или загрузка Microsoft Word (Microsoft Word Error 5941).

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

  • Remove From My Forums
  • Question

  • I have looked at some of the explanations and suggested cures but they are not simple enough for me.  I am trying to make a macro which will insert my address etc on a blank document.  I have the address layout stored in Quick Parts, so having
    brought up a blank normal document on screen, I usually go to Quick Parts and insert the block and then back to Home before proceeding.  I wanted to have a Quick Access macro which would do that.  So I am bringing up the blank, going into record
    Macro and assigning to button and recording then to Quick Parts, selecting the address, Insert, and then back to Home, before Stop Recording.    However, when I try to run the macro, I get the 5941 message each and every time.  On debug
    the whole macro is highlighted.

    I did make a successful macro for PrintPage which was fine and I use it all the time.  I have Windows 7 64 bit and Word 2010 Office and Student.

Answers

  • Sounds right. Like this?

    Sub Macro1()

    ‘ Macro1 Macro

    Templates.LoadBuildingBlocks 
        Application.Templates( _
            «C:UsersJosephineAppDataRoamingMicrosoftDocument Building Blocks103314Building Blocks.dotx» _
            ).BuildingBlockEntries(«HomeAddress»).Insert Where:=Selection.Range, _
            RichText:=True
    End Sub


    Enjoy,
    Tony
    www.WordArticles.com

    • Marked as answer by

      Monday, July 18, 2011 6:52 AM

  • Hi «Boots»

    I was going to suggest the same thing as Tony and am as surprised as he that it didn’t work. The next step would be to narrow down whether the «missing member» of the collection refers to the template or to the Building Block entry. So let’s break the recorded
    macro down into smaller pieces and see exactly where the problem is coming from. Try something like this and tell us which line gets highlighted:

    Sub Macro1()
      Dim tmpl as Word.Template
    
      Application.Templates.LoadBuildingBlocks 
      Set tmpl = Application.Templates( _
        "C:UsersJosephineAppDataRoamingMicrosoftDocument Building Blocks103314Building Blocks.dotx")
     
       tmpl.BuildingBlockEntries("HomeAddress").Insert Where:=Selection.Range, _
        RichText:=True
    End Sub
    

    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Calvin_Gao
      Monday, July 18, 2011 6:51 AM

  • Hi «Boots»

    I’m amazed that just pulling the stuff apart worked. Word never ceases to amaze me…

    In order to give a macro a different name, simply change what appears after the word «Sub». To name the macro InsertMyAddress, for example, change the line

      Sub Macro1()

    to

      Sub InsertMyAddress()

    To assign this to your Quick Access Toolbar (QAT), click on the arrow that points down at the very end of the QAT. Choose «More commands…» This should open the File/Options dialog box at the correct «tab». From the dropdown list at the top left choose
    «Macros». Click on the macro, then click the button to ADD it to the list on the right. If you want to see a different icon, click on the macro in the list on the right, then click «Modify». There you can choose a picture and change the «Display name».

    (I’m looking at Word 2007, where the names of things are a bit different. That’s why I’m not giving you the exact menu names — I don’t want to confuse you!)


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Calvin_Gao
      Monday, July 18, 2011 6:51 AM

 

ddmitriy

Пользователь

Сообщений: 5
Регистрация: 01.10.2014

#1

21.06.2017 17:17:09

Добрый день.
При вставке фотографии в шаблон Word выскакивает ошибка «5941 Запрашиваемый номер семейства не существует»

Код
With WD
Picture_count = Picture_count + 1
    .Bookmarks("pic1").Range.Select
    FolderPic = Replace(ThisWorkbook.FullName, ThisWorkbook.Name, "Pic1")
    Dim coll As Collection
    If Dir(FolderPic, vbDirectory) = "" Then
        MsgBox "No Folder Pic1" & folder$ & "»", vbCritical, "No Folder "
        GoTo pict_1
    End If
    Set coll = FilenamesCollection(FolderPic, ".jpg")
    For i = 1 To coll.Count
          
       WA.Selection.InlineShapes.AddPicture Filename:=coll.Item(i)
       WA.Selection.TypeParagraph
    Next i
pict_1: End With

Ошибка указывает на строку.

Код
.Bookmarks("pic1").Range.Select

Закладки проверил, всё в норме. Подскажите что ещё может быть не так.

Спасибо.

 

The_Prist

Пользователь

Сообщений: 14009
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Ответ один — его действительно не существует. Если Вы в одну и ту же закладку в цикле что-то пытаетесь записать, то это вполне возможно, т.к. после первой записи закладка как правило удаляется.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#3

21.06.2017 17:34:49

покажите весь код
возможно не правильно обращаетесь к документу либо обращаетесь к неактивному документу с командой select
попробуйте

Код
wd.Activate
 wd.Bookmarks("pic1").Range.Select

Спасибо

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#4

21.06.2017 17:49:06

Цитата
The_Prist написал:
т.к. после первой записи закладка как правило удаляется.

——
Если использовать не диапазон (кусок) текста в закладке, а положение курсора, то ничего не удаляется :))

Спасибо

 

The_Prist

Пользователь

Сообщений: 14009
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Дмитрий, в данном случае активация избыточна, т.к. идет обращение к закладкам конкретного документа: WD. Поэтому озвученная ошибка не может возникнуть по этой причине. Если бы активен был другой документ, то была бы другая ошибка.

Изменено: The_Prist21.06.2017 17:50:14

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#6

21.06.2017 17:51:01

The_Prist,  Поэтому и прошу старттопика показать весь кусок кода. Что там у него за WD только он знает :)

Спасибо

 

ddmitriy

Пользователь

Сообщений: 5
Регистрация: 01.10.2014

#7

21.06.2017 17:54:07

R Dmitry? не помогло.
Весь код:

Скрытый текст

 

The_Prist

Пользователь

Сообщений: 14009
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#8

21.06.2017 17:54:37

Цитата
R Dmitry написал:
Если использовать не диапазон

если кусок — да, не удалится. Но у ТС-а же не так :)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

How to fix the Runtime Code 5941 Microsoft Word Error 5941

This article features error number Code 5941, commonly known as Microsoft Word Error 5941 described as Error 5941: Microsoft Word has encountered a problem and needs to close. We are sorry for the inconvenience.

About Runtime Code 5941

Runtime Code 5941 happens when Microsoft Word fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.

Definitions (Beta)

Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!

  • Microsoft word — For programming questions related to Microsoft’s «Word» editor

Symptoms of Code 5941 — Microsoft Word Error 5941

Runtime errors happen without warning. The error message can come up the screen anytime Microsoft Word is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.

There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.

Fix Microsoft Word Error 5941 (Error Code 5941)
(For illustrative purposes only)

Causes of Microsoft Word Error 5941 — Code 5941

During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.

Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.

Repair Methods

Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.

If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.

Please note: Neither ErrorVault.com nor it’s writers claim responsibility for the results of the actions taken from employing any of the repair methods listed on this page — you complete these steps at your own risk.

Method 1 — Close Conflicting Programs

When you get a runtime error, keep in mind that it is happening due to programs that are conflicting with each other. The first thing you can do to resolve the problem is to stop these conflicting programs.

  • Open Task Manager by clicking Ctrl-Alt-Del at the same time. This will let you see the list of programs currently running.
  • Go to the Processes tab and stop the programs one by one by highlighting each program and clicking the End Process buttom.
  • You will need to observe if the error message will reoccur each time you stop a process.
  • Once you get to identify which program is causing the error, you may go ahead with the next troubleshooting step, reinstalling the application.

Method 2 — Update / Reinstall Conflicting Programs

Using Control Panel

  • For Windows 7, click the Start Button, then click Control panel, then Uninstall a program
  • For Windows 8, click the Start Button, then scroll down and click More Settings, then click Control panel > Uninstall a program.
  • For Windows 10, just type Control Panel on the search box and click the result, then click Uninstall a program
  • Once inside Programs and Features, click the problem program and click Update or Uninstall.
  • If you chose to update, then you will just need to follow the prompt to complete the process, however if you chose to Uninstall, you will follow the prompt to uninstall and then re-download or use the application’s installation disk to reinstall the program.

Using Other Methods

  • For Windows 7, you may find the list of all installed programs when you click Start and scroll your mouse over the list that appear on the tab. You may see on that list utility for uninstalling the program. You may go ahead and uninstall using utilities available in this tab.
  • For Windows 10, you may click Start, then Settings, then choose Apps.
  • Scroll down to see the list of Apps and features installed in your computer.
  • Click the Program which is causing the runtime error, then you may choose to uninstall or click Advanced options to reset the application.

Method 3 — Update your Virus protection program or download and install the latest Windows Update

Virus infection causing runtime error on your computer must immediately be prevented, quarantined or deleted. Make sure you update your virus program and run a thorough scan of the computer or, run Windows update so you can get the latest virus definition and fix.

Method 4 — Re-install Runtime Libraries

You might be getting the error because of an update, like the MS Visual C++ package which might not be installed properly or completely. What you can do then is to uninstall the current package and install a fresh copy.

  • Uninstall the package by going to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package.
  • Click Uninstall on top of the list, and when it is done, reboot your computer.
  • Download the latest redistributable package from Microsoft then install it.

Method 5 — Run Disk Cleanup

You might also be experiencing runtime error because of a very low free space on your computer.

  • You should consider backing up your files and freeing up space on your hard drive
  • You can also clear your cache and reboot your computer
  • You can also run Disk Cleanup, open your explorer window and right click your main directory (this is usually C: )
  • Click Properties and then click Disk Cleanup

Method 6 — Reinstall Your Graphics Driver

If the error is related to a bad graphics driver, then you may do the following:

  • Open your Device Manager, locate the graphics driver
  • Right click the video card driver then click uninstall, then restart your computer

Method 7 — IE related Runtime Error

If the error you are getting is related to the Internet Explorer, you may do the following:

  1. Reset your browser.
    • For Windows 7, you may click Start, go to Control Panel, then click Internet Options on the left side. Then you can click Advanced tab then click the Reset button.
    • For Windows 8 and 10, you may click search and type Internet Options, then go to Advanced tab and click Reset.
  2. Disable script debugging and error notifications.
    • On the same Internet Options window, you may go to Advanced tab and look for Disable script debugging
    • Put a check mark on the radio button
    • At the same time, uncheck the «Display a Notification about every Script Error» item and then click Apply and OK, then reboot your computer.

If these quick fixes do not work, you can always backup files and run repair reinstall on your computer. However, you can do that later when the solutions listed here did not do the job.

Other languages:

Wie beheben Fehler 5941 (Microsoft Word-Fehler 5941) — Fehler 5941: Microsoft Word hat ein Problem festgestellt und muss geschlossen werden. Wir entschuldigen uns für die Unannehmlichkeiten.
Come fissare Errore 5941 (Errore 5941 di Microsoft Word) — Errore 5941: Microsoft Word ha riscontrato un problema e deve essere chiuso. Ci scusiamo per l’inconveniente.
Hoe maak je Fout 5941 (Microsoft Word-fout 5941) — Fout 5941: Microsoft Word heeft een probleem ondervonden en moet worden afgesloten. Excuses voor het ongemak.
Comment réparer Erreur 5941 (Erreur Microsoft Word 5941) — Erreur 5941 : Microsoft Word a rencontré un problème et doit se fermer. Nous sommes désolés du dérangement.
어떻게 고치는 지 오류 5941 (마이크로소프트 워드 오류 5941) — 오류 5941: Microsoft Word에 문제가 발생해 닫아야 합니다. 불편을 끼쳐드려 죄송합니다.
Como corrigir o Erro 5941 (Erro 5941 do Microsoft Word) — Erro 5941: O Microsoft Word encontrou um problema e precisa fechar. Lamentamos o inconveniente.
Hur man åtgärdar Fel 5941 (Microsoft Word-fel 5941) — Fel 5941: Microsoft Word har stött på ett problem och måste avslutas. Vi är ledsna för besväret.
Как исправить Ошибка 5941 (Ошибка Microsoft Word 5941) — Ошибка 5941: Возникла ошибка в приложении Microsoft Word. Приложение будет закрыто. Приносим свои извинения за неудобства.
Jak naprawić Błąd 5941 (Błąd Microsoft Word 5941) — Błąd 5941: Microsoft Word napotkał problem i musi zostać zamknięty. Przepraszamy za niedogodności.
Cómo arreglar Error 5941 (Error 5941 de Microsoft Word) — Error 5941: Microsoft Word ha detectado un problema y debe cerrarse. Lamentamos las molestias.

The Author About The Author: Phil Hart has been a Microsoft Community Contributor since 2010. With a current point score over 100,000, they’ve contributed more than 3000 answers in the Microsoft Support forums and have created almost 200 new help articles in the Technet Wiki.

Follow Us: Facebook Youtube Twitter

Last Updated:

09/11/22 08:52 : A Windows 10 user voted that repair method 1 worked for them.

Recommended Repair Tool:

This repair tool can fix common computer problems such as blue screens, crashes and freezes, missing DLL files, as well as repair malware/virus damage and more by replacing damaged and missing system files.

STEP 1:

Click Here to Download and install the Windows repair tool.

STEP 2:

Click on Start Scan and let it analyze your device.

STEP 3:

Click on Repair All to fix all of the issues it detected.

DOWNLOAD NOW

Compatibility

Requirements

1 Ghz CPU, 512 MB RAM, 40 GB HDD
This download offers unlimited scans of your Windows PC for free. Full system repairs start at $19.95.

Article ID: ACX08352EN

Applies To: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Speed Up Tip #26

Changing My Documents Folder Location:

Free up some space in your system partition drive by moving the My Documents folder to another partition. This will speed up your computer by giving it more space to breathe. It will also allow for an easy data backup and recovery in case of Windows system crash.

Click Here for another way to speed up your Windows PC

  • Remove From My Forums
  • Question

  • Hello All,

    Below is the macro, I have been using to connect to the SQL server to fetch the data. I tried to make a little change to the macro by adding the tab space (Selection.TypeText vbTab). The macro works perfect when, I add single(Selection.TypeText vbTab) but
    when I add more than one (Selection.TypeText vbTab) tabs to the code I get Runtime Error 5941.  I’ve indicated the vbtabs in bold type and the the actual error after hitting Debug in Underline Type. Can somebody give me hand on this?

    Thanks

    Sub InsertBarcode()
    
    Dim strcode As String
    Dim canConnect As Boolean
    Dim longname As String
    
    
    Dim StrCode1 As String
    
    Dim cnn As ADODB.Connection
       Dim Customer As ADODB.Recordset
       Set cnn = New ADODB.Connection
       Set Customer = New ADODB.Recordset
    
     
       cnn.ConnectionString = "DSN=SQLDSN; UID=TestMacro; PWD=sql123"
    cnn.Open
    If cnn.State = adStateOpen Then
          'MsgBox "Connection Successful to Database!"
    
    StrCode1 = Trim(InputBox("Please enter the Job Number", "Barcode Insertion"))
    strcode = "SELECT custcode,Custname FROM Job where JobNumber='" & Trim(StrCode1) & "'"
    
    If StrCode1 = "" Then Exit Sub
    With Selection
         With Customer
            Set .ActiveConnection = cnn
            .Source = strcode
            .Open
            Do
                If .EOF Then Exit Do
                'MsgBox (Customer.Fields("CustomerCode"))
                 'MsgBox (Customer.Fields("CustLongName"))
                'ActiveDocument.Range.Text = Customer.Fields("CustomerCode")
                If Customer.Fields("CustomerCode") = "" Then
                
                Else
                Call CustomerName(Customer.Fields("CustLongName"), "Calibri (Body)", 36)
                'ActiveDocument.Range.Text = Customer.Fields("CustLongName")
                End If
                
                .MoveNext
            Loop
        
          .Close
          End With
         
    
      .Collapse wdCollapseStart
      .Text = StrCode1
      
      Selection.Font.size = 36
      Selection.Font.Bold = False
      'Selection.MoveRight
      'Selection.TypeText vbTab
     
      StrCode1 = "QUOTE " & """*" & StrCode1 & "*"" * Charformat"
     
      'Selection.MoveLeft
      
      
        .Collapse wdCollapseStart
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=StrCode1, PreserveFormatting:=False
        Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
         'Selection.InsertBreak Type:=wdLineBreak
        .Start = .Start - 2
      
    With .Fields(1).Code.Characters(2)
        
        .Font.Name = "Free 3 of 9 Regular"
        
        .Font.size = 36
        
      End With
      
    
      .Fields(1).Update
      
    End With
     
    cnn.Close
    Else
          MsgBox "No Connection To Server Has Been Established"
          End If
    End Sub
    
    Sub CustomerName(insert_string As Variant, Font As String, size As Integer)
    ' Insert the string in insert_string after the current search position.
    Dim wdApp As Word.Application
    Dim oRng As Range
    Dim Rows_Written As Long
    Set wdApp = Word.Application
    Set oRng = wdApp.Selection.Range
    With oRng
        '.Start = .Paragraphs(1).Range.End
        .InsertParagraphAfter
        .Start = .End
        .Text = CStr(insert_string)
        '.Font.Name = Font
        .Font.Bold = False
        '.Font.Underline = wdUnderlineSingle
        .Font.size = 14
        .InsertParagraphAfter
    End With
    Rows_Written = Rows_Written + 2
    End Sub
    
    
    
    
    
    
    

  • Remove From My Forums
  • Question

  • Hello All,

    Below is the macro, I have been using to connect to the SQL server to fetch the data. I tried to make a little change to the macro by adding the tab space (Selection.TypeText vbTab). The macro works perfect when, I add single(Selection.TypeText vbTab) but
    when I add more than one (Selection.TypeText vbTab) tabs to the code I get Runtime Error 5941.  I’ve indicated the vbtabs in bold type and the the actual error after hitting Debug in Underline Type. Can somebody give me hand on this?

    Thanks

    Sub InsertBarcode()
    
    Dim strcode As String
    Dim canConnect As Boolean
    Dim longname As String
    
    
    Dim StrCode1 As String
    
    Dim cnn As ADODB.Connection
       Dim Customer As ADODB.Recordset
       Set cnn = New ADODB.Connection
       Set Customer = New ADODB.Recordset
    
     
       cnn.ConnectionString = "DSN=SQLDSN; UID=TestMacro; PWD=sql123"
    cnn.Open
    If cnn.State = adStateOpen Then
          'MsgBox "Connection Successful to Database!"
    
    StrCode1 = Trim(InputBox("Please enter the Job Number", "Barcode Insertion"))
    strcode = "SELECT custcode,Custname FROM Job where JobNumber='" & Trim(StrCode1) & "'"
    
    If StrCode1 = "" Then Exit Sub
    With Selection
         With Customer
            Set .ActiveConnection = cnn
            .Source = strcode
            .Open
            Do
                If .EOF Then Exit Do
                'MsgBox (Customer.Fields("CustomerCode"))
                 'MsgBox (Customer.Fields("CustLongName"))
                'ActiveDocument.Range.Text = Customer.Fields("CustomerCode")
                If Customer.Fields("CustomerCode") = "" Then
                
                Else
                Call CustomerName(Customer.Fields("CustLongName"), "Calibri (Body)", 36)
                'ActiveDocument.Range.Text = Customer.Fields("CustLongName")
                End If
                
                .MoveNext
            Loop
        
          .Close
          End With
         
    
      .Collapse wdCollapseStart
      .Text = StrCode1
      
      Selection.Font.size = 36
      Selection.Font.Bold = False
      'Selection.MoveRight
      'Selection.TypeText vbTab
     
      StrCode1 = "QUOTE " & """*" & StrCode1 & "*"" * Charformat"
     
      'Selection.MoveLeft
      
      
        .Collapse wdCollapseStart
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=StrCode1, PreserveFormatting:=False
        Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
       Selection.TypeText vbTab
         'Selection.InsertBreak Type:=wdLineBreak
        .Start = .Start - 2
      
    With .Fields(1).Code.Characters(2)
        
        .Font.Name = "Free 3 of 9 Regular"
        
        .Font.size = 36
        
      End With
      
    
      .Fields(1).Update
      
    End With
     
    cnn.Close
    Else
          MsgBox "No Connection To Server Has Been Established"
          End If
    End Sub
    
    Sub CustomerName(insert_string As Variant, Font As String, size As Integer)
    ' Insert the string in insert_string after the current search position.
    Dim wdApp As Word.Application
    Dim oRng As Range
    Dim Rows_Written As Long
    Set wdApp = Word.Application
    Set oRng = wdApp.Selection.Range
    With oRng
        '.Start = .Paragraphs(1).Range.End
        .InsertParagraphAfter
        .Start = .End
        .Text = CStr(insert_string)
        '.Font.Name = Font
        .Font.Bold = False
        '.Font.Underline = wdUnderlineSingle
        .Font.size = 14
        .InsertParagraphAfter
    End With
    Rows_Written = Rows_Written + 2
    End Sub
    
    
    
    
    
    
    

When running the macro I am getting the following error:

«Runtime Error ‘5941’ The Requested Member of Collection Does Not Exist»

The line below is highlighted in Yellow; This Macro works on the majority of users and the error has only been reported off two users.

Windows(DestTemplateName).Document.Bookmarks("fCustomer").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCust").Range.Fields(1).Result.Text

Any Help Would Be Much Appreciated.

Sub PopulateBookingForm()

Dim SourceTemplateName As String, DestTemplateName As String

' Set Method Statement Name
SourceTemplateName = ActiveDocument.Name

' Open Heavy Cranes ICO Booking Form
ChangeFileOpenDirectory "\SERVERSHAREHCDHCD GeneralTemplates"
Documents.Open FileName:= _
    "\SERVERSHAREHCDHCD GeneralTemplatesHeavy Cranes ICO Booking Form.docx", _
    ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
    PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
    WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
    wdOpenFormatAuto, XMLTransform:=""
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

' Set Haulage Booking Form Document Name
DestTemplateName = ActiveDocument.Name

' ### START FIND AND REPLACE

' Populate Customer(Client)
Windows(DestTemplateName).Document.Bookmarks("fCustomer").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCust").Range.Fields(1).Result.Text

' Populate Version
Windows(DestTemplateName).Document.Bookmarks("fVersion").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fRevision").Range.Fields(1).Result.Text

' Populate Entered Onto CRM
Windows(DestTemplateName).Document.Bookmarks("fEnteredOntoCRM").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fEnteredOntoCRM").Range.Fields(1).Result.Text

' Populate CRM Opportunity Name
Windows(DestTemplateName).Document.Bookmarks("fCRMOportunityName").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCRMOportunityName").Range.Fields(1).Result.Text

' Populate Contact Name
Windows(DestTemplateName).Document.Bookmarks("fContactName").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteContact").Range.Fields(1).Result.Text

' Populate Telephone No (Mobile)

If Replace(Windows(SourceTemplateName).Document.Bookmarks("fSiteMobile").Range.Fields(1).Result.Text, ChrW(8194), "") = "" Then
    Windows(DestTemplateName).Document.Bookmarks("fTelephoneNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteTel").Range.Fields(1).Result.Text
Else
    Windows(DestTemplateName).Document.Bookmarks("fTelephoneNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteMobile").Range.Fields(1).Result.Text
End If

' Populate Fax No(Email)
Windows(DestTemplateName).Document.Bookmarks("fFaxNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteFax").Range.Fields(1).Result.Text

' Populate Site Address
Windows(DestTemplateName).Document.Bookmarks("fSiteAddress").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteAddr").Range.Fields(1).Result.Text

' Populate Duration
Windows(DestTemplateName).Document.Bookmarks("fDuration").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fDuration").Range.Fields(1).Result.Text

' Populate Date of Hire/RFW
Windows(DestTemplateName).Document.Bookmarks("fTimeReadyForWork").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("dt1").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fDayDateOfHire").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("dt1").Range.Fields(1).Result.Text

' Populate Inspector
Windows(DestTemplateName).Document.Bookmarks("fFormCompletedBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fSiteVisitedBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fMethodStatementBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text

' Populate CL
Windows(DestTemplateName).Document.Bookmarks("fCL").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fTermsCL").Range.Fields(1).Result.Text

' Populate CH
Windows(DestTemplateName).Document.Bookmarks("fCH").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fTermsCH").Range.Fields(1).Result.Text

' Populate Wires
Windows(DestTemplateName).Document.Bookmarks("fWires").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryWires").Range.Fields(1).Result.Text

' Populate Web Slings
Windows(DestTemplateName).Document.Bookmarks("fWebSlings").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryWebSlings").Range.Fields(1).Result.Text

' Populate Beams
Windows(DestTemplateName).Document.Bookmarks("fBeams").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryBeams").Range.Fields(1).Result.Text

' Populate Chains
Windows(DestTemplateName).Document.Bookmarks("fChains").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryChains").Range.Fields(1).Result.Text

' Populate Shackles
Windows(DestTemplateName).Document.Bookmarks("fShackles").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryShackles").Range.Fields(1).Result.Text

' Populate Other
Windows(DestTemplateName).Document.Bookmarks("fOther").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryOthers").Range.Fields(1).Result.Text

' Populate Job Description
Windows(DestTemplateName).Document.Bookmarks("fJobDescription").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fDescOfWorks").Range.Fields(1).Result.Text & vbNewLine & vbNewLine & Windows(SourceTemplateName).Document.Bookmarks("fOperReqACHL").Range.Fields(1).Result.Text

' Populate Other Information
Windows(DestTemplateName).Document.Bookmarks("fOperationByClient").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fOperReqClient").Range.Fields(1).Result.Text

' ### END FIND AND REPLACE

' Activate New Document
Windows(DestTemplateName).Activate
End Sub

The Macro Basically Copies Some Text From Fields In The Source Document Over To The Destination Document.

Понравилась статья? Поделить с друзьями:
  • Ошибка runtime error 5 invalid procedure call or argument
  • Ошибка runtime error 5 at 00403fa4
  • Ошибка runtime error 438
  • Ошибка runtime error 424 object required
  • Ошибка runtime error 339 windows 10