Visual basic not working in excel

Symptoms

In Microsoft Office Excel, Microsoft Visual Basic for Application (VBA) macro code that is contained «behind» a worksheet or workbook may not work correctly.

Cause

This will occur if both of the following conditions are true:

  • The code in question is contained inside an automatically-running subroutine, such as an Auto_Open or Auto_Close subroutine.

  • The code is not contained in a Visual Basic module, but «behind» a worksheet or the workbook itself.

Workaround

In order for automatically-running subroutines to work correctly in Microsoft Excel, they must be contained within a Visual Basic module.

You must insert a Visual Basic module into the workbook and then place the code in the new module.

To insert a Visual Basic module:

  1. In the Project Explorer in the Visual Basic Editor, activate the workbook that contains the code in question.

  2. On the Insert menu, click Module.

After the new module is inserted, cut the code from its original location and paste it into the Visual Basic module. Then, save the workbook.

More Information

In Excel, VBA code can be stored in three different locations: in a Visual Basic module, in a Visual Basic class module, and «behind» worksheets and workbooks.

To edit code «behind» a worksheet or a workbook:

  1. Activate the Visual Basic Editor (press ALT+F11).

  2. In the Project Explorer window, you will see entries similar to the following:

        
         VBAProject (Book1)
         Microsoft Excel Objects
            Sheet1 (Sheet1)
            Sheet2 (Sheet2)
            Sheet3 (Sheet3)
            ThisWorkbook         
         Modules
             Module1

If you double-click one of the worksheet names or ThisWorkbook, you can type code in the code window. Such code not contained within a Visual Basic module is considered to be «behind» the worksheet or
ThisWorkbook .

If an Auto_Open, Auto_Close, or other automatically-running subroutine is stored «behind» a worksheet or ThisWorkbook, it may not function correctly when you open or close your workbook, or when you perform an action that should cause the subroutine to run.

Need more help?

Download PC Repair Tool to quickly find & fix Windows errors automatically

While using Microsoft Visual Basic for Applications on Excel, if you get Run-time errorClass not registered, here is how you can fix the issue. It is pretty common when there are some issues with the code or Office installation. That is why you can follow these tips and tricks to get rid of this problem.

Fix VBA Run-time error Class not registered in Excel

You can run various codes via Visual Basic on an Excel spreadsheet to get different things done within moments and in automation. However, while running such a code, if you get the aforementioned error, you won’t be able to do what you were looking forward to. If so, you can follow the subsequent solutions to get rid of the error, as mentioned above.

To fix Microsoft Visual Basic Run-time error Class not registered in Excel, follow these steps:

  1. Check the code
  2. Update Excel/Office
  3. Turn on trust access to VBA
  4. Repair Microsoft Office

To learn more about these steps, continue reading.

1] Check the code

It is the very first thing you need to check when you are getting the aforementioned error in Excel. If the entered or written code is wrong, the argument is missing, etc., you won’t be able to run it on your spreadsheet. As a result, you might get the error as said above. That is why it is recommended to verify the code before running it again or heading to other solutions.

Read: How to create Custom Excel Functions using VBA

2] Update Excel/Office

Fix VBA Run-time error Class not registered in Excel

If you haven’t updated Excel or Office for a very long time, it is recommended to do that. At times, Microsoft might change various things, and that could be a reason why you are getting such an error. To update Office, do the following:

  • Open Excel on your computer.
  • Click on the Account.
  • Expand the Update Options.
  • Click the Update Now option.

Then, it will search for a pending update and install it accordingly.

3] Turn on Trust access to VBA

Fix VBA Run-time error Class not registered in Excel

When you are getting this error, you must check if this setting is turned on or not. If not, it is suggested to enable it on your computer. To turn on trust access to the VBA project, follow these steps:

  • Open Excel and click on Options.
  • Switch to the Trust Center tab.
  • Click the Trust Center Settings button.
  • Go to the Macro Settings tab.
  • Tick the Trust access to the VBA project object model checkbox.
  • Click the OK button.

Then, restart Excel and check if the problem remains or not.

4] Repair Microsoft Office

Fix VBA Run-time error Class not registered in Excel

It is the last thing you need to do in order to troubleshoot the error. To repair Office on Windows 11/10, do the following:

  • Press Win+I to open Windows Settings.
  • Go to Apps > Apps & features.
  • Click the three-dotted button of Microsoft 365.
  • Select the Modify option.
  • Click the Yes button in the UAC prompt.
  • Choose the Online Repair option.
  • Click the Repair button.

Once the process is done, you can restart your computer and check if the problem is resolved or not.

Apart from trying these solutions, you can also run the System File Checker. At times, an internal conflict can cause the above-mentioned error. If so, you can fix it with the help of SFC Scan.

How do I fix Runtime error in Excel VBA?

To fix the Run-time error in Excel VBA, you need to follow the above-mentioned solutions. You should start the troubleshooting process by verifying the code. However, if nothing works, you must repair the Office installation. In that case, select the Online Repair option instead of Quick Repair.

Read: How to fix Runtime Error 1004 in Microsoft Excel

How do I bypass VBA error in Excel?

There is no way to bypass the VBA error in Excel if you want to use the code. You must resolve the issue in order to use it without any error. A detailed guide of four solutions as mentioned above, and it is recommended to follow all of them to troubleshoot the VBA error in Excel.

Related: How to fix VBA error 400 in Excel.

Ezoic

When he is not writing about Microsoft Windows or Office, Sudip likes to work with Photoshop. He has managed the front end and back end of many websites over the years. He is currently pursuing his Bachelor’s degree.

I want to elaborate a bit the comment of mine which was correct suggestion.

First, let me repeat that- you need to switch on events in this way

Application.EnableEvents = true

which you can be run once in Immediate Window in VBA/IDE Editor. Now we know that was it!

Second, if you decided to switch on events using any other subroutine (or event, which is however strange) please keep in mind that there could be some other subroutines, functions or add-ins which require events to be switched off. As long as you are not sure why events are not working you should keep them not working right after your macro doesn’t need them any more. Therefore, my suggestion is to switch events off each time you will close your file. Therefore you could add this event to ThisWorkbook module:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.EnableEvents = False
End Sub

Extra tip. The best option would be to read events status at the beginning, keep this information until you close your file. You could do it in the following steps:

A) declare public variables in your file

Public boEventsStatus as Boolean

B) read status when opening file (you need to figure it out where put this line of code)

boEventsStatus = Application.EnableEvents

C) switch on events as described at the beginning

D) use this BeforeClose event:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.EnableEvents = boEventsStatus
End Sub

 

Дома запустил Exel но в нем не работает редактор VB
Может где нибудь выключил его?)

 

VSerg

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

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

Настройки безопасности скорее всего.

 

Astroid1

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

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

Что значит не работает редактор VB?

Это пробовали:

Файл — > Параметры — > настройка ленты -> флажок активен на строке «Разработчик»
ALT+F11

?

 

Alex Deroza

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

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

#4

07.03.2017 14:55:13

Разработчик стоит, Ф11 не реагирует.

Цитата
VSerg написал: Настройки безопасности скорее всего.

Походу, но где?)

 

Пытливый

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

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

А на чем запустили?

Кому решение нужно — тот пример и рисует.

 

VSerg

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

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

У меня в меню Разработчик

Прикрепленные файлы

  • Capture.PNG (22.11 КБ)

 

на винде, на чем же еще.. 2016 версия офиса

 

всё равно не хочет открывать ВБ
Он не активен. Скрыт. Как будто его выключили где то..

вот такое при запуске файла..
И даже при попытке создать новый файл, чистый, с макро расширением, нет доступа к исходному коду..

Изменено: Alex Deroza07.03.2017 15:33:29

 

VSerg

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

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

Обсуждалось

похожее

. Вроде как переустановка офиса помогла.

 

Только хотел дописать что бы не просили переустановить офис ))))))))

 

БМВ

Модератор

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

Excel 2013, 2016

А установлен ли у вас  этот компонент? Возможно вопрос глупый, но буквально год назад на виртуалку ставил и для минимизации поотключал всё включая это, зацепив случайно.
 

Изменено: БМВ07.03.2017 15:44:14

По вопросам из тем форума, личку не читаю.

 

Можно как нибудь посмотреть на это через PS или CMD? Просто у меня пиратский версия.. и такого нету..

Изменено: Alex Deroza07.03.2017 15:46:35

 

БМВ

Модератор

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

Excel 2013, 2016

#13

07.03.2017 15:52:57

Цитата
Alex Deroza написал:
Можно как нибудь посмотреть на это через PS или CMD?

Если это вопрос ко мне, то не исследовал этот момент. Скорее нет чем да, но это моно посмотреть через контрольную панель программы и компоненты офис ..  ну и там выбрать добавить и удалить компоненты.  

По вопросам из тем форума, личку не читаю.

  • Remove From My Forums
  • Question

  • I just wrote my question on the other forum and realised this forum is the right one to ask VBA questions.

    I have just changed to Windows 7 (64 bit) last Friday and I tested with a few VBA codes by using Excel 2010 that I have used in other OS (XP, Vista) there has been no problems. But with Windowns 7 it is having some issues. What I tried to do is to read
    picture pixels on Excel spreadsheet. Running through each cells within the Picture range, and output pixels in each cells. 

    I found VBA turns into ‘Not Responding’ quickly after running the code. Then i found even i run on very simply code on given ‘Range’. Excel stop running  and change to ‘Not Responding’

    I am now thinking that it may be a change in system environment. Or maybe it has something to do with 64 bit.

     I was wondering if anybody has had this experience yet and what the resolution to it.

    Thanks for your time.

    Below is the simple code I am testing. when you start running, you will see Cursor quickly move through each cell (as i select each cell), but after a while, the Cursor suddenly stop moving and excel changes to ‘Not responding’, then after a few seconds, cursor
    jump to the end of the range… very strange , it run without any problem in XP with excel 2007 even 2003. I am not sure if anybody has known about this issue?

    Sub TestPoints()
     Dim MyCell As Range
    Dim Irow As Integer
    Dim MaxRows As Integer
    Dim Icol As Integer
    Dim MaxCols As Integer

    MaxRows = 250
    MaxCols = 350

        For Irow = 1 To MaxRows
            For Icol = 1 To MaxCols
            Cells(Irow, Icol).Select
            Next Icol
        Next Irow

       
    End Sub

Answers

  • Hello,

    And if you insert a «Doevents» ?

    Sub TestPoints()

    Dim MyCell As Range

    Dim Irow As Integer

    Dim MaxRows As Integer

    Dim Icol As Integer

    Dim MaxCols As Integer

    MaxRows = 250

    MaxCols = 350

        For Irow = 1 To MaxRows

           For Icol = 1 To MaxCols

           Cells(Irow, Icol).Select

           DoEvents

           Next Icol

       Next Irow

    End Sub

     Does it change anything ?

    • Marked as answer by

      Tuesday, March 29, 2011 7:10 PM

  • I can confirm that Excel 2010 32 bit on Win 64 does stop responding, but only for a few seconds. I re-wrote the code as:

    Sub TestPoints2()
    Dim Rng As Range
        Application.ScreenUpdating = False
        For Each Rng In Range(«A1», Cells(250, 350))
            Rng.Select
            DoEvents
        Next Rng
        Beep
        Application.ScreenUpdating = True
    End Sub

    I agree with CharAbeuh, Do events is a good idea.


    Rod Gill

    The one and only Project VBA Book
    Rod Gill Project Management

    • Marked as answer by
      supershirley
      Tuesday, March 29, 2011 7:10 PM

Понравилась статья? Поделить с друзьями:
  • Visual basic microsoft word 2007
  • Visual basic in excel for mac
  • Visual basic for word and excel
  • Visual basic for excel процедуры
  • Visual basic for excel для начинающих