Microsoft visual basic for applications ошибка 400

Struggling with the Excel VBA error 400 while trying to run macros, then read the article to learn how to fix Excel 2016 macro error 400...

Are you getting an error dialog box titled Microsoft Excel that contains only the number 400? Or getting the error message VBA error 400 Excel 2016, then this article is for you.

Here check out the complete information about Excel 2016 macro error 400.

Microsoft Excel is a very crucial file and not free from errors. There are many cases seen when many different types of errors crop up and interrupt the users from time to time.

The Excel 2016 error 400 is the one that many users are found reporting. Excel Error 400 is related to the VBA or the Macro. Some users are getting the VBA error 400 while running an Excel Macros.

Despite this, it is also seen it is caused due to improperly configured settings or due to irregular Windows registry entries.

Well, this is very irritating and there is no exact reason behind what causes the VBA 400 error in Excel. Here check out some of the possible causes.

To repair corrupt Excel file, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

Why I am getting Excel VBA Error Code 400?

There is no exact reason for getting the VBA error 400 in Excel 2016, some of the common causes like VBA corruption or the macros you are trying to run is corrupt and many others.

  • Due to incorrect or failed installation or un-installation of software
  • Invalid Registry entries
  • Due to an error in the macro that was running
  • The external error like failure to read or write from a file.
  • The arguments contain the value that is not valid
  • While trying to gain access to an object that does not exist
  • The macros you are trying to run is corrupted
  • The properties and method of VBE object for manipulation VBA code stored in Office document are by default inaccessible.

So these are some of the possible reasons that might cause the VBA error 400 while running Excel Macros.

Now try the possible fixes to resolve the Excel error 400.

How To Fix Excel 2016 Macro 400 Error?

Just like the reasons the solution to resolve the VBA error 400 macros also varies. So here check out the possible solutions like moving the macros to the new module, turning on trusted access to VBA, and others to fix VBA error 400.

Solution 1: Move The Macros To New Module

It might happen due to some kind of external error you are getting the Visual Basic error 400 in Excel.

So try creating a module in VBA and click on Insert>module and move the macros to the new module. Also, assure deleting the original one.

Hope this resolves the VBA error 400 in Excel macros, if not then try the second possible solution.

Solution 2: Turn On Trusted Access To VBA

Sometimes when you are trying to gain access to the VBA project the users start getting the VBA error 400 in Excel. So here try to turn on trusted access to Visual Basic Projects.

Follow the steps to do so:

  1. Try going to the Developer tab. But, if the Developer tab is unavailable, then follow the steps to display it:
    • First, click File > Options > Customize Ribbon.
    • Then under Main Tabs > choose the Developer checkbox.
  2. Now, in the Code group > on the Developer tab > click Macro Security.
  3. And under Developer Macro Settings > choose the Trust access to the VBA project object model checkbox.

Hope turning on the trusted access to VBA fixes the Excel 2016 macro 400 error.

Apart from that also check the codes you are entering as some mistakes in codes may cause Excel error 400. Also, check for the macros corruption before trying to run them.

Don’t Miss: Top Ways to Recover Macros from Corrupted Excel File Effectively

Hope the given manual solutions work for you to resolve the VBA error 400 running an Excel Macros. But if not then try the automatic repair utility to resolve the VBA error 400 in Excel.

Automatic Solution: MS Excel Repair Tool

It is recommended to make use of the MS Excel Repair Tool. It is the best tool to repair all sorts of issues, corruption, errors in Excel workbooks. This is the best tool that just by scanning once detects and fixes various errors in Excel files and repairs and recover damaged, corrupted, or even inaccessible Excel files as well.

It allows you to easily restore all corrupt Excel files including the charts, worksheet properties cell comments, and other important data. This is a unique tool to repair multiple Excel files at one repair cycle and recovers the entire data in a preferred location. It is easy to use and compatible with both Windows as well as Mac operating systems.

* Free version of the product only previews recoverable data.

Steps to Utilize MS Excel Repair Tool:

Final Verdict:

That’s it; I have done my job, now it’s your turn to follow the fixes to resolve VBA error 400 in Excel.

Follow the given manual solutions to fix Visual Basic error 400 in Excel. Also, scan your Excel file with the automatic repair utility to fix other Excel issues responsible for getting the error.

Apart from that Excel is a very crucial file so it is very important to handle it properly and backup your important data to avoid data loss situations.

In case you have any additional workarounds that proved successful or questions concerning the ones presented, do tell us in the comments or you can visit the Repair MS Excel Facebook and Twitter account.

Good Luck…

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

In this Article

  • Ensure that VBA Projects are Trusted
  • Transfer Your Code to a New Module
  • Debug and Review the VBA Code
  • Repair or Reinstall Microsoft Office
  • Check Your System for Malware or Viruses

This article will demonstrate how to fix Excel VBA Error 400.

Error 400 occurs while a VBA macro is running, usually causing the macro to crash and stop running. It is a very annoying error that can be quite difficult to resolve but by following the methods below you can hopefully solve your problem!

Ensure that VBA Projects are Trusted

First, that your VBA Projects are trusted.   To ensure that they are, follow these steps:

In the Ribbon, select File > Options and then (1) select Trust Center and (2) Trust Center Settings.

vba error 400 excel-options

OR

In the Ribbon, select Developer > Macro Security.

vba error macro security

Note: If you don’t see the Developer Ribbon, you’ll need to enable it.

Then,  select (1) Macro Settings. Ensure that (2) Trust access to the VBA project object model is checked and then (3) click OK.

vba error 400 trust center

Transfer Your Code to a New Module

If you still encounter the error, the issue might be a corrupt code module.

To ensure that the code module is not corrupt, transfer your code to a new module and then delete the old module.

1) To insert a new module, we need to open the Visual Basic Editor (VBE).

In the Ribbon, select Developer > Visual Basic.

vba error VBE

Or Press Alt+F11 to switch to the VBE.

2) Make sure you have the correct VBA Project selected and then, in the Menu, select Insert > Module.

vba-error 400 menu insert module

3) Click in the original module and press CTRL + A on they keyboard to select all the code. Then copy the code (CTRL + C or right-click and select COPY)

vba error 400 copy code

4) Click in your new module and Paste the copied code into this module (CTRL + V).

5) Then right-click on your original module (in this case Module1), and select Remove Module1 to remove it from your VBA project.

vba-error 400 remove module

Or in the Menu, select File > Remove Module1.

6) Save your workbook to keep your changes.

Debug and Review the VBA Code

An Error 400 could also occur due to incorrect VBA code. The VBA Editor contains a variety of debugging tools. A powerful one is the ability to step through your code.

Click in the procedure that you wish to debug and then, in the Menu, select Debug > Step Into  OR press F8 on the keyboard.

vba error 400 debug

The procedure name will then be highlighted in yellow indicating that you are now in Debug mode.

vba error 400 debug mode

You can then go through your code line by line by pressing F8 each time to move down to the next line.

By debugging your code in this manner, you can check that it all runs correctly and does not raise the error 400

Repair or Reinstall Microsoft Office

If all of the above suggestions do not help, you may unfortunately have to repair or reinstall Microsoft Office as you may have a corrupt installation or corrupt registry entry.

First, try repairing the installed version of Office.

In the Settings App in your PC, select Apps > Apps and Features and then scroll down the list until your find your installation of Microsoft Office.

Click on the Modify button, select Online Repair or Quick Repair and then click Repair.

Re-boot your PC and try your macro again.

If this does not help, you may have to remove Microsoft Office from your machine by uninstalling it and then re-install it.

Check Your System for Malware or Viruses

Finally, do make sure that your system is checked for both Malware and Viruses as these can also lead to this Error 400.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

В этой статье мы обсудим методы исправления ошибки VBA 400 в Excel. Ошибка 400 в Excel обычно возникает при запуске макроса Microsoft Visual Basic для приложений (VBA). Это вызывает сбой макроса или сбой при запуске и возвращает сообщение об ошибке 400. Причины такой ошибки могут быть разными; давайте обсудим их.

vba-error-400-в-Excel

Что вызывает ошибку VBA 400 в Excel?

Вот причины, из-за которых возникает ошибка 400 при запуске макроса в Excel:

  • Неправильная установка программного обеспечения Office.
  • В коде VBA есть ошибка.
  • Недопустимое значение аргумента.
  • Запущенный макрос поврежден.
  • Файлы, связанные с Excel, заражены каким-либо вредоносным ПО.
  • Ошибка чтения / записи из файла.
  • Неверные записи в реестре.

Если вы столкнулись с ошибкой 400 в Excel, вы можете использовать перечисленные ниже решения для ее устранения.

Вот способы исправить ошибку 400, возникшую при запуске макроса в Excel:

  1. Переместите макросы в новый модуль.
  2. Включите доверенный доступ к VBA.
  3. Просмотрите свой код VBA.
  4. Восстановите Microsoft Excel.
  5. Удалите, а затем повторно установите Excel.
  6. Некоторые другие методы, такие как сканирование на наличие вредоносных программ и т. Д.

Давайте подробно обсудим эти методы.

1]Переместить макросы в новый модуль

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

Перейдите на вкладку «Разработчики» и выберите «Визуальный редактор». Если вы не видите вкладку «Разработчики» на главной ленте в Excel, перейдите в «Файл»> «Параметры» и на вкладке «Настройка лент» установите флажок «Разработчики» в разделе «Основные вкладки».

Теперь в окне Microsoft Visual Basic для приложений щелкните меню «Вставка» и выберите параметр «Модуль».

После этого вставьте код макроса в этот новый модуль и сохраните его, используя специальную опцию в меню «Файл».

Кроме того, вам нужно удалить старый модуль, щелкнув его правой кнопкой мыши и используя Удалять вариант.

Наконец, щелкните Файл> Закрыть и вернуться в Microsoft Excel и посмотрите, устранена ли ошибка 400 в Excel.

2]Включить надежный доступ к VBA

Вы можете включить доверенный доступ к VBA и посмотреть, исчезла ли проблема. Вот шаги, чтобы включить доверенный доступ к VBA:

  1. Перейдите на вкладку «Разработчики» и нажмите «Безопасность макросов».
  2. В окне центра управления безопасностью включите параметр Надежный доступ к объектной модели проекта VBA.
  3. Нажмите кнопку ОК.

3]Проверьте свой код

Ошибка в коде VBA может вызвать ошибку 400 в Excel. Итак, вам необходимо тщательно просмотреть код макроса и исправить ошибку в коде, если таковая имеется. Также проверьте макросы на наличие повреждений.

4]Восстановить Microsoft Excel

Если ничего из вышеперечисленного не работает, проблема может быть в приложении Excel. Возможно, приложение установлено неправильно или что-то нужно исправить. Итак, восстановите Microsoft Excel, используя следующие шаги:

  1. Запустите приложение «Настройки» и выберите «Приложения»> «Приложения и функции».
  2. Справа найдите и щелкните Программа Office 365 / Microsoft 365.
  3. Нажмите на кнопку «Изменить», а затем выберите вариант «Онлайн-ремонт» или «Быстрое восстановление».
  4. Нажмите кнопку «Восстановить», чтобы восстановить Excel и другие приложения Office.

5]Удалите, а затем повторно установите Excel.

Вы также можете попробовать удалить, а затем переустановить программное обеспечение Office и Excel, чтобы начать заново. Посмотрите, устраняет ли это ошибку.

6]Некоторые другие методы

Кроме того, некоторые другие решения также могут работать, например:

  • Вы можете попробовать запустить сканирование SFC, чтобы проверить и восстановить поврежденные системные файлы.
  • Некоторые вредоносные программы также могут вызывать эту ошибку. Итак, проверяйте и удаляйте вредоносные программы и подозрительные приложения с помощью Microsoft Defender или сторонней антивирусной или антивредоносной программы.
  • Попробуйте удалить поврежденные данные кеша и системные ненужные файлы.

Надеюсь, что приведенные выше решения помогут!

Теперь прочтите: Как исправить ошибку выполнения 1004 в Excel

vba-error-400-в-Excel .

error 400 in VBA

Introduction

It is often said that debugging is part of programming, and through error messages, the programmer can easily identify where there are problems in his/her code. But as you can see from the above screenshot the VBA Error 400 is one of those annoying types of error that does not give you any information on the origin of the bug of your code.

You only know that there is an error because you see the red cross on the message box with the number 400 referring to the error number.  If as a VBA coder you have come across the VBA error 400 and do not know what to do, then this article is for you.

In the following article, we shall see the possible causes of this error (there are many of them) and how to fix them.

What Are the Causes of VBA Error 400?

Excel error 400 occurs when Microsoft Excel fails or crashes while running. This can be caused by many factors. The following are the most common:

  • Infected download or deficient installation of Microsoft Excel software
  • Invalid registry entries
  • Windows system files or Microsoft Excel-related program files infected by malware or a virus
  • Microsoft Excel-connected files maliciously or wrongly deleted by another program
  • Error in a macro; or the macro that you are trying to run is corrupt
  • Failure to read or write from a file or trying to get access to an object that does not exist
  • Attack on the device or disk storage system including the MS Excel related data files and folders by malware or virus

Note: VBA 400 error messages can arise in any of the following Microsoft Windows operating systems: Windows 10, Windows 8, Windows 7, Windows Vista, Windows XP, Windows ME, Windows 2000.

How to Fix Microsoft Excel Error 400

The VBA 400 error message does not give any indication on the origin of the error. Consequently, you might have to try one or a combination of the methods below to fix the problem. However, I strongly advise you to check your macro very well to be certain that the error is not coming from the code itself before attempting any fix.

Transfer macros to a new module

Step 1: Select the developer tab on the Excel menu and click on the Visual Basic option or Click on Alt + F11 simultaneously.

open vba editor

Step 2: Select the Insert tab of the VBA Editor and click on the Module option or click on Tools > Macro then name the macro and press Enter

Insert module into VBA editor

Step 3: Paste the VBA code that you want to use.

Step 4: Navigate to the File menu and click on Save Global.

Note: Make sure to delete the old module.

Switch on Trusted Access to VBA

Step 1: Select the Developer tab on the Excel menu, go to the Code group and click on Macro Security.

Macro security in Excel

Step 2:  Under “Developer Macro Settings” check “Trusted Access to the VBA project.”

Trust access to the VBA project object model

Other More Advanced Methods

If the solutions above have not solved your problem, then you should resolve to try the ones below.

Warning: If you are not versed in registry manipulation and related activities, I suggest you work with an expert on these solutions.

  1. Scan your device to remove harmful malware and viruses from the system.
  2. Remove system junk files and corrupted cache data.
  3. Next, update the PC with the latest system drivers.
  4. Try to “undo” all the recently made changes to the device through Windows System Restore files.
  5. Uninstall each suspicious application, including the corrupted MS Excel app. Then, reinstall a fresh version.
  6. Next, run the Windows System File Checker (SFC) scan to detect and delete corrupted system files.
  7. Now, install the latest Windows OS update.
  8. Finally, run a clean installation of Windows.

Automatic Solution

Beside the manual solutions explained above, there is also an automatic solution called the MS Excel Repair Tool. It is a highly recommended and one of the most appropriate tools to repair all sort of issues, corruption, errors in Excel workbooks. Just by scanning once, the tool detects and fixes various errors in Excel file and repair and recover damaged, corrupted or even inaccessible Excel file as well.

It allows you to easily restore all corrupt Excel file including the charts, worksheet properties, cell comments, and other important data. This is a unique tool to repair multiple Excel files in one repair cycle and recovers the entire data in a preferred location. It is easy to use and compatible with both Windows (http://www.repairmsexcel.com/blog/free-download-for-win)  as well as Mac operating system (http://www.repairmsexcel.com/blog/free-download-for-mac ).

Make sure you double-check your code as errors can easily creep in.

by Vlad Turiceanu

Passionate about technology, Windows, and everything that has a power button, he spent most of his time developing new skills and learning more about the tech world. Coming… read more


Published on August 17, 2022

Reviewed by
Radu Tyrsina

Radu Tyrsina

Radu Tyrsina has been a Windows fan ever since he got his first PC, a Pentium III (a monster at that time). For most of the kids of… read more

  • Excel Macro represents a set of commands and actions that are triggered by a VBA code.
  • As handy as it has proven to be, VBA is no stranger to errors especially if you write the code yourself.
  • The VBA error 400 is quite common and usually appears if your Macro fails or crashes whilst it’s running.
  • Don’t worry, we have prepared 3 easy fixes for you to try in order to remove this pesky error for good.

how to resolve VBA error 400

When you have a set of actions that you do constantly, creating a Macro in Excel is crucial.

Once you create it, it runs on its own and delivers great reports. That is if you don’t get any error.

Some users seem to be getting a VBA error 400 when trying to run their Macro in Excel. There are no further indications only a box with an OK button.

How can I solve VBA error 400 in Excel?

Either way, don’t worry we have some simple solutions for you.

We suggest that you follow the steps mentioned in this article in the presented order. Hopefully, they will help you solve your problem.

1. Fix VBA error 400 by moving your Macros to another Module

If you are getting the VBA error 400 in Excel while trying to run your Macros, moving them to a new Module can fix it.

There could be a problem with the old Module, therefore switching to a new one might fix the error.

1. Open Microsoft Excel.

2. We need to create the new Module to transfer your Macros to. Click on the Developer tab from the Ribbon menu.

how to fix vba error 404 developer tab

3. Select Visual Basic from the options.

visual basics how to fix vba error 400

4. In the VBA menu, click Module on the Insert menu.

fix vba error 400 select module

5. Paste the VBA code that you want to use.

6. Navigate to the File menu and click Save Global. Now your Macros are successfully moved to the new Module.

7. Delete the old module.

2. Fix VBA error 400 by turning on the trusted access

how to resolve excel VBA error message
  1. Go to the Developer tab (If this is not available click File > Options > Customise Ribbon > choose the Developer checkbox).
  2. In the  Code group – go to the Developer tab.
  3. Click Macro Security.
  4. Select Developer Macro Settings – choose Trusted access to the VBA project.
Read more about this topic

  • Error 0x80004005: 9 Expert Tips to Fix the Unspecified Error
  • Microsoft Excel is Waiting for Another Application to Complete OLE Action
  • Fix: Most of The Features Have Been Disabled [Word, Excel]

3. Check your code for mistakes to fix VBA error 400

how to fix VBA error in excel macros

Make sure to always check your code for any mistakes. Additionally, checking for any macros corruption is necessary as well.

That’s about it. We hope that doing these confirmed solutions will fix your VBA 400 Error. In case you have other confirmed suggestions please let us know in a comment below.

Still having issues? Fix them with this tool:

SPONSORED

If the advices above haven’t solved your issue, your PC may experience deeper Windows problems. We recommend downloading this PC Repair tool (rated Great on TrustPilot.com) to easily address them. After installation, simply click the Start Scan button and then press on Repair All.

newsletter icon

Newsletter

  • Remove From My Forums
  • Question

  • Excel Version:  2010 Business Pro

    Problem:  I have a macro that is getting to a certain line of code then encountering an Error 400 («Form Already Displayed; Can’t Show Modally»; don’t really understand what this error is).  I am including the code for
    the macro below.  You will note in the code below, where the macro bombs out.  I didn’t bother including code for any of the other called macros since they don’t seem to be the problem. 

    Any suggestions would be welcome.  The Msgboxes are for debugging only.

    Regards,

    …bob sutor

    PageBreaksRows_Button MACRO CODE:

    Public Sub PageBreakRows_Button()

    ‘On Error GoTo ErrorHandler1:

    ‘TURN OFF FEATURES TO SPEED UP MACRO PROCESSING:
        If c = 0 Then _
        PerformanceOptionsOFF

       
    ‘SETACTIVE SHEETNAME
        Dim strPageBreaksSheetName As String
        Dim strReferenceSheetName As String
        Dim intErrorCount As Integer

       
        strPageBreaksSheetName = ActiveSheet.Name
        strReferenceSheetName = «5005-PageBreaks»

       
        vrZoom = 75
        intPaperSize = 1 ‘ 1 = Letter, 17 = 11×17
        intOrientation = 1 ‘ 1= Portrait, 2 = Landscape

       
    ‘SET SOURCE SHEET STATUS
        blnSourceSheetVisibleStatus = ActiveSheet.Visible
        ActiveSheet.Visible = True

        blnSourceSheetProtectStatus = ActiveSheet.ProtectContents
        ActiveSheet.Unprotect Password:=strPassword

       
    100 Answer = MsgBox(«Do you want to proceed with resetting all page breaks on active sheet?», vbOKCancel)
        Select Case Answer
            Case vbOK
                strPageBreaksAddRemove = «Add»
                ActiveSheet.ResetAllPageBreaks
                ‘Reset print parameters after page breaks reset
                Sheets(strPageBreaksSheetName).PageSetup.Zoom = vrZoom
                Sheets(strPageBreaksSheetName).PageSetup.Orientation = intOrientation
                Sheets(strPageBreaksSheetName).PageSetup.PaperSize = intPaperSize

            Case vbCancel
                GoTo 500
            End Select

       
    ‘CHECK TO SEE IF NECESSARY RANGE NAMES exist, if not setup
        If Not NameExists_ActiveSheet(«PageBreaksActiveSheetSetup») Then
            MsgBox «PageBreaksActiveSheetSetup missing on 5005-PageBreaks sheet (Worksheet Scope)»
            intErrorCount = intErrorCount + 1
            End If
        If Not NameExists_Workbook(«PageBreaks5005Reference») Then
            MsgBox «PageBreaks5005Reference missing on 5005-PageBreaks sheet (Workbook Scope)»
            intErrorCount = intErrorCount + 1
            End If
        If Not NameExists_Workbook(«PageBreaksSheetRowNumbers») Then
            MsgBox «PageBreaksSheetRowNumbers missing on 5005-PageBreaks sheet (Workbook Scope)»
            intErrorCount = intErrorCount + 1
            End If

           
        If intErrorCount > 0 Then GoTo 500

    400
    ‘SET VALUE OF SHEET REFERENCE IN 5005-PagBreaks to ActiveSheet.Name and calculate
        MsgBox «TEST ONLY:  strReferenceSheetName = » & strReferenceSheetName & «; strPageBreaksSheetName = » & strPageBreaksSheetName
        MsgBox «TEST ONLY:  Active Sheet Name on 5005:  » & Sheets(strReferenceSheetName).Range(«PageBreaks5005Reference»).Value & «, Active Sheet Name » & strPageBreaksSheetName
        Sheets(strReferenceSheetName).Range(«PageBreaks5005Reference»).Value = strPageBreaksSheetName
        Application.Calculate   ‘THIS IS WHERE THE MACRO STOPS AND GENERATES ERROR 400

       
    ‘RUN MACRO TO SET PAGE BREAKS:
     MsgBox «TEST ONLY: Call PageBreaksActiveSheet macro from M03_ActiveSheet_Macros Module», vbOKOnly
            c = c + 1
            Call PageBreaksActiveSheet
            c = c — 1
     MsgBox «TEST ONLY: PageBreaksActiveSheet macro ran successfully», vbOKOnly
    500
    ‘RETURN SOURCE SHEET TO ORIGINAL HIDE & PROTECT STATUS
        ‘Return SOURCE Sheet to original protect status
         If blnSourceSheetProtectStatus = True Then
            c = c + 1
            ProtectActiveSheet
            c = c — 1
            End If

       
        ‘Return SOURCE Sheet to original visible status
            Sheets(strPageBreaksSheetName).Activate
            ActiveSheet.Visible = blnSourceSheetVisibleStatus

          
    ‘TURN PROGRAM FEATURES BACK ON:
        PerformanceOptionsON

       
    Exit Sub

    ErrorHandler1:
    ‘RETURN SOURCE SHEET TO ORIGINAL HIDE & PROTECT STATUS
        ‘Return SOURCE Sheet to original protect status
         If blnSourceSheetProtectStatus = True Then
            c = c + 1
            ProtectActiveSheet
            c = c — 1
            End If

       
        ‘Return SOURCE Sheet to original visible status
            Sheets(strPageBreaksSheetName).Activate
            ActiveSheet.Visible = blnSourceSheetVisibleStatus

       
    ‘TURN PROGRAM FEATURES BACK ON:
        PerformanceOptionsON

       
        ‘On Error display message
        MsgBox («Macro has encountered an error, call » & strSupportContact)
        MsgBox «Error» & Err & «: » & Error(Err.Number)

    End Sub


    Bob Sutor

Answers

  • I am the developer.  Do you really think a developer would let some who didn’t even know how to set a break point in VBE debug this macro? 

    Bob,

    Excuse me, but also many novice ask questions in this forum, it is not easy to distinguish. Therefore, I already give the note before the next question is how to do that.

    The easiest way to understand the difference between vbModal and vbModeless in relation to the RTE 400 is an example. Please make a new file, add a userform, add a command button on that form and this code into the code module:

    Private Sub CommandButton1_Click()
      UserForm2.Show
    End Sub

    Then add another userform, also a command button on that form and this code:

    Private Sub CommandButton1_Click()
     UserForm1.Show
    End Sub

    Then add a regular module and this code:

    Sub Main()
      UserForm1.Show
    End Sub

    When you run Main, the 1st form is shown. Now try to select a cell in the worksheet, you can’t. That means this child window is modal and you have to close it first when you want to return to the parent window.

    Click the command button and the 2nd form is shown, move the window a little so that you can see the first form. Now try to select the 1st form, you can’t. The relation between the 2nd and the 1st form is the same as the 1st form and the parent window.

    Click the command button on the 2nd form and you get the RTE 400.

    You can break the relationship between the windows when you shown them non-modal, resp. mode less.

    Change the code of Userform1 to this:

    Private Sub CommandButton1_Click()
      UserForm2.Show vbModeless
    End Sub

    And run sub Main again. When you click the command button, you get a RTE 401, read the description carefully, it is very similar to the RTE 400.

    Now change the code in the regular module to this:

    Sub Main()
      UserForm1.Show vbModeless
    End Sub

    And run that sub. Now try to select a cell in the worksheet, it is possible! When you click the command button the 2nd form opens. Now try to select a cell in the worksheet or the 1st form, it is possible! But when you click the command button on the 2nd form
    you get the RTE 400 again.

    Change the code in Userform2 to this:

    Private Sub CommandButton1_Click()
     UserForm1.Show vbModeless
    End Sub

    Run sub Main, the 1st form opens, click the command button the 2nd form opens. Click the command button and the RTE 400 is gone.

    So whatever happens when you get the RTE 400 in your file, IMHO there are windows involved. Maybe you can’t see them on screen, because it is possible to show windows hidden and/or to totally disable the screen output of a window. Who opens them? I don’t know.

    If there aren’t windows involved, then you might have a bigger problem and your application can crash next time. In that case the RTE 400 is only a symptom. I’ve mostly seen that when API calls are used incorrectly and therefore some memory problems caused.

    Andreas.

    • Edited by

      Sunday, January 5, 2014 12:22 PM

    • Marked as answer by
      ConstPM
      Sunday, January 5, 2014 6:32 PM

Понравилась статья? Поделить с друзьями:
  • Microsoft visual basic for applications compile error the code in this
  • Microsoft visual basic for applications compile error in hidden module excel
  • Microsoft visual basic error run time error 1004
  • Microsoft visual c runtime library runtime error что это
  • Microsoft visual basic compile error can t find project or library