How to fix VBA error 400 in Excel
In this article, we are going to discuss methods on how to fix VBA error 400 in Excel. The error 400 in Excel usually occurs while running a Microsoft Visual Basic for Applications (VBA) macro. It causes the macros to crash or fail to run and return an error 400 message. Now, there can be different reasons for such an error; let us discuss them.
What causes VBA error 400 in Excel?
Here are the reasons due to which error 400 is triggered when running a Macro in Excel:
- Faulty installation of the Office software.
- There is some error in the VBA code.
- Invalid value in the argument.
- The running macro is corrupted.
- Excel-related files infected by some malware.
- Failure to read/ write from a file.
- Invalid registry entries.
If you are encountering error 400 in Excel, you can use the below-listed solutions to resolve it.
How to fix VBA error 400 in Excel
Here are the methods to fix error 400 encountered while running a macro in Excel:
- Move Macros to a new Module.
- Enable trusted access to VBA.
- Review your VBA code.
- Repair Microsoft Excel.
- Uninstall, and then reinstall Excel.
- Some other methods like scan for malware, etc.
Let us discuss these methods elaborately.
1] Move Macros to a new Module
Transferring your macros to a new module may fix the issue in case there is some external error. You can use the below steps to do so:
Go to the Developers tab and click on the Visual editor option. In case you don’t see the Developers tab on the main ribbon in Excel, go to File > Options and from Customize Ribbons tab, turn on the Developers checkbox from the Main Tabs section.
Now, in the Microsoft Visual Basic for Applications window, click on the Insert menu and then the Module option.
After that, paste your Macro code into this new module and save it using the dedicated option from the File menu.
Also, you need to delete the old module by right-clicking it and using the Remove option.
At last, click the File > Close and Return to Microsoft Excel option and see if the error 400 is resolved in Excel.
2] Enable trusted access to VBA
You can turn on the trusted access to VBA and see if the issue is gone. Here are the steps to enable trusted access to VBA:
- Move to the Developers tab and click on the Macros Security option.
- In the Trust Centre window, enable the option named Trusted access to the VBA project object model.
- Press the OK button.
3] Review your code
An error in VBA code can trigger error 400 in Excel. So, you need to thoroughly review the macro code and correct the error in the code if any. Also, check macros if there is any corruption.
4] Repair Microsoft Excel
If none of the above works, the problem might be with the Excel app. The application might be installed incorrectly or something needs to be repaired. So, repair Microsoft Excel using the below steps:
- Launch Settings app and go to Apps > Apps & features.
- On the right, locate and click Office 365/ Microsoft 365 program.
- Tap on the Modify button and then select Online Repair or Quick Repair option.
- Press the Repair button which repairs Excel and other Office apps.
5] Uninstall, and then reinstall Excel
You can also try to uninstall and then reinstall Office and Excel software to start afresh. See if this fixes up the error.
6] Some Other Methods
Also, some other solutions may also work like:
- You can try running an SFC scan to check and repair corrupted system files.
- Some malicious programs can also cause this error. So, check and remove malware and suspicious application with Microsoft Defender or third-party antivirus or antimalware program.
- Try deleting corrupted cache data and system junk files.
Excel 400 vba error
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
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.
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
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
VBA Error 400: What Is It And How to Fix It [3 Easy Ways]
Make sure you double-check your code as errors can easily creep in.
- 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.
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.
3. Select Visual Basic from the options.
4. In the VBA menu, click Module on the Insert menu.
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
- Go to the Developer tab (If this is not available click File >Options >Customise Ribbon > choose the Developer checkbox).
- In the Code group – go to the Developer tab.
- Click Macro Security.
- Select Developer Macro Settings – choose Trusted access to the VBA project.
Read more about this topic
3. Check your code for mistakes to fix VBA error 400
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:
Как исправить ошибку VBA 400 в Excel
В этой статье мы обсудим методы исправления ошибки VBA 400 в Excel. Ошибка 400 в Excel обычно возникает при запуске макроса Microsoft Visual Basic для приложений (VBA). Это вызывает сбой макроса или сбой при запуске и возвращает сообщение об ошибке 400. Причины такой ошибки могут быть разными; давайте обсудим их.
Что вызывает ошибку VBA 400 в Excel?
Вот причины, из-за которых возникает ошибка 400 при запуске макроса в Excel:
- Неправильная установка программного обеспечения Office.
- В коде VBA есть ошибка.
- Недопустимое значение аргумента.
- Запущенный макрос поврежден.
- Файлы, связанные с Excel, заражены каким-либо вредоносным ПО.
- Ошибка чтения / записи из файла.
- Неверные записи в реестре.
Если вы столкнулись с ошибкой 400 в Excel, вы можете использовать перечисленные ниже решения для ее устранения.
Как исправить ошибку VBA 400 в Excel
Программы для Windows, мобильные приложения, игры — ВСЁ БЕСПЛАТНО, в нашем закрытом телеграмм канале — Подписывайтесь:)
Вот способы исправить ошибку 400, возникшую при запуске макроса в Excel:
- Переместите макросы в новый модуль.
- Включите доверенный доступ к VBA.
- Просмотрите свой код VBA.
- Восстановите Microsoft Excel.
- Удалите, а затем повторно установите Excel.
- Некоторые другие методы, такие как сканирование на наличие вредоносных программ и т. Д.
Давайте подробно обсудим эти методы.
1]Переместить макросы в новый модуль
Перенос макросов в новый модуль может решить проблему в случае внешней ошибки. Для этого вы можете использовать следующие шаги:
Перейдите на вкладку «Разработчики» и выберите «Визуальный редактор». Если вы не видите вкладку «Разработчики» на главной ленте в Excel, перейдите в «Файл»> «Параметры» и на вкладке «Настройка лент» установите флажок «Разработчики» в разделе «Основные вкладки».
Теперь в окне Microsoft Visual Basic для приложений щелкните меню «Вставка» и выберите параметр «Модуль».
После этого вставьте код макроса в этот новый модуль и сохраните его, используя специальную опцию в меню «Файл».
Кроме того, вам нужно удалить старый модуль, щелкнув его правой кнопкой мыши и используя Удалять вариант.
Наконец, щелкните Файл> Закрыть и вернуться в Microsoft Excel и посмотрите, устранена ли ошибка 400 в Excel.
2]Включить надежный доступ к VBA
Вы можете включить доверенный доступ к VBA и посмотреть, исчезла ли проблема. Вот шаги, чтобы включить доверенный доступ к VBA:
- Перейдите на вкладку «Разработчики» и нажмите «Безопасность макросов».
- В окне центра управления безопасностью включите параметр Надежный доступ к объектной модели проекта VBA.
- Нажмите кнопку ОК.
3]Проверьте свой код
Ошибка в коде VBA может вызвать ошибку 400 в Excel. Итак, вам необходимо тщательно просмотреть код макроса и исправить ошибку в коде, если таковая имеется. Также проверьте макросы на наличие повреждений.
4]Восстановить Microsoft Excel
Если ничего из вышеперечисленного не работает, проблема может быть в приложении Excel. Возможно, приложение установлено неправильно или что-то нужно исправить. Итак, восстановите Microsoft Excel, используя следующие шаги:
- Запустите приложение «Настройки» и выберите «Приложения»> «Приложения и функции».
- Справа найдите и щелкните Программа Office 365 / Microsoft 365.
- Нажмите на кнопку «Изменить», а затем выберите вариант «Онлайн-ремонт» или «Быстрое восстановление».
- Нажмите кнопку «Восстановить», чтобы восстановить Excel и другие приложения Office.
5]Удалите, а затем повторно установите Excel.
Вы также можете попробовать удалить, а затем переустановить программное обеспечение Office и Excel, чтобы начать заново. Посмотрите, устраняет ли это ошибку.
6]Некоторые другие методы
Кроме того, некоторые другие решения также могут работать, например:
- Вы можете попробовать запустить сканирование SFC, чтобы проверить и восстановить поврежденные системные файлы.
- Некоторые вредоносные программы также могут вызывать эту ошибку. Итак, проверяйте и удаляйте вредоносные программы и подозрительные приложения с помощью Microsoft Defender или сторонней антивирусной или антивредоносной программы.
- Попробуйте удалить поврежденные данные кеша и системные ненужные файлы.
Надеюсь, что приведенные выше решения помогут!
Теперь прочтите: Как исправить ошибку выполнения 1004 в Excel
.
Программы для Windows, мобильные приложения, игры — ВСЁ БЕСПЛАТНО, в нашем закрытом телеграмм канале — Подписывайтесь:)