Vba ошибка runtime error 6 overflow

I have been trying to resolve this but could not. I have the following VBA code. While running it gives «run time error 6: Overflow». I guess I have assigned a right type to each variable. Please help!!

Sub UseCoeff()
Dim a, b As Long
Dim Value1 As Double

ThisWorkbook.Sheets("UseTableBEA").Activate
For b = 2 To 427
    For a = 2 To 431

        Value1 = ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value
        ThisWorkbook.Sheets("UseCoeff").Cells(a, b).Value = Value1

    Next a
Next b
End Sub

Each cell will have a result that may be between 0 and 1 up to eight decimal places.
Thanks in advance!!

Community's user avatar

asked Sep 18, 2012 at 3:05

user1671860's user avatar

1

If ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value is ever 0, then ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value will cause the Overflow error if ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value is also 0.

To avoid this, use an if statement to filter out the 0s, just update the comment with the actual logic you want:

If ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value = 0 Then
    Value1 = 'Whatever you want but probably 0.
Else
    Value1 = ThisWorkbook.Sheets("UseTableBEA").Cells(a, b).Value / ThisWorkbook.Sheets("UseTableBEA").Cells(432, b).Value
End If

answered Sep 18, 2012 at 4:18

Daniel's user avatar

DanielDaniel

13k2 gold badges36 silver badges60 bronze badges

2

Dim a, b As Long

a is not declared as a long it is declared as a variant try this:

Dim a as long, b as Long

Edit:
Having tested this, it still produces a Stack Overflow error. However it is good practice to declare your variables properly.

You also don’t need this line:

ThisWorkbook.Sheets("Sheet1").Activate

and if you declare UseTableBEA you can slim down your code:

Dim Ws1 as Worksheet
Set Ws1 = Sheets("UseTableBEA")

You can then use Ws1 where you have previously used ThisWorkbook.Sheets("UseTableBEA")

answered Sep 18, 2012 at 12:47

Alistair Weir's user avatar

Alistair WeirAlistair Weir

1,8096 gold badges26 silver badges47 bronze badges

0

Summary:
The VBA runtime error 6 in Microsoft Excel can occur due to various reasons. In this post, we will understand the causes behind this VBA runtime error and discuss the methods to resolve the error. We will also mention an Excel repair tool that can help fix this error if the cause is corruption in Excel file.

Free Download for Windows

Contents

  • Some of the error messages related to this error include:
  • Causes of VBA Runtime Error Code 6
  • Methods to Fix VBA Error Code 6 in Microsoft Excel
  • Conclusion

The runtime (overflow) error 6 in Microsoft Excel usually occurs when you declare a number to the variable but that number is outside the parameters of the specific data type. The data type inbuilt into the VBA denotes the value type you can store in a variable and the range of values you can hold in the variable. For example, a Byte can store values between 0 and 255 and an Integer can store values from -32768 to 32768. So, if you enter a value that is more than the assigned value, then you’ll get the VBA runtime error 6 (overflow).

Some of the error messages related to this error include:

  • “Excel VBA Error Code 6 Overflow”
  • “Cannot run Excel VBA Error Code 6 Overflow”
  • “Excel VBA Error Code 6 Overflow cannot be located”
  • “Excel VBA Error Code 6 Overflow not found”
  • “Excel VBA Error Code 6 Overflow needs to be closed”
  • “Fault in software path: Excel VBA Error Code 6 Overflow”

Causes of VBA Runtime Error Code 6

Though the runtime error 6 in MS Excel usually occurs due to incorrect value in the variable, there are various other reasons that can lead to this error. Here are some other common causes of the error:

  • Conflicting programs.
  • Bad graphics driver.
  • Corruption in Microsoft Excel file.
  • Updates, such as Microsoft Visual C++, are not installed properly.

Methods to Fix VBA Error Code 6 in Microsoft Excel

You need to understand the data types before declaring a variable. However, to fix the issue, you can change the VBA data type or assign a proper value in the variable based on the data type. If the issue still persists, then follow the below methods.

Method 1: Close Conflicting Programs

You may encounter the runtime error when multiple programs conflict with each other. Closing these conflicting programs can resolve the error. Here are the steps:

  • Press Ctrl+Shift+Esc at the same time to open the Task Manager.
  • Stop the programs one-by-one by clicking the End Process button.
  • Check if the error message stops displaying when you stop a process. This will help you identify which program was causing the error.

Method 2: Update Virus Protection Software

Virus infection can lead to the corruption of Excel files, resulting in runtime error 6. Ensure that your antivirus program is updated. If not, update it and scan the system properly.

Method 3: Reinstall Microsoft Visual C++

Runtime errors can occur if updates such as Microsoft Visual C++ are not installed properly. You can reinstall the current Microsoft Visual C++ package to resolve the error. Follow these steps:

  • Go to Programs and Features and find the Microsoft Visual C++ redistributable package.
  • Click Uninstall.
  • Once the uninstallation process is complete, reboot your system.
  • Download and install the latest redistributable package.

Method 4: Reinstall Graphic Driver

This error may also occur if the graphic driver is damaged or outdated. If the runtime error has occurred because of a bad graphic driver, follow these steps to resolve the issue.

  • Open Device Manager and locate the installed graphic driver.
  • Right-click on the driver and click Uninstall.
  • Restart your system. Windows will automatically install the driver.

Method 5: Run Disk Cleanup

The runtime error might occur due to low storage on your system. You can run Disk Cleanup to free up space on your system. Follow the below instructions:

  • Take a backup of your files on your external hard drive to free up some space.
  • Clear your cache and restart the system.
  • Open Explorer Window and right-click on your system drive (usually C:)
  • Click Properties and then click on Disk Cleanup.
From the General tab, click on Disk Cleanup

Method 6: Repair the Excel File

Runtime error 6 can also occur due to a corrupted or damaged Excel file. If this is the case, you can repair your Excel file using the Open and Repair utility in Excel. Here’s how:

  • Open Excel and click File > Open.
  • Select the folder that contains the affected file.
  • In the Open dialog box, click on the file.
  • Click on the arrow next to the Open option.
  • Click Open and Repair from the given options.

From the Open window, select the file and click on Open and Repair

  • Click Repair to recover as much data from the workbook as possible.

In the Dialog box, click on Repair to extract data

  • After repair, you will see a message as shown in the below figure.

After Repairing, click on Close.

  • Click Close.

If the above utility fails to resolve the issue, using an advanced Excel repair tool can do the job for you. Stellar Repair for Excel is one such tool that can quickly repair Excel files and restore all the data, such as tables, pivot tables, charts, formulas, etc. with 100% integrity. This tool can help fix all types of errors in Excel related to corruption.

Conclusion

If you are facing the VBA runtime error 6 in MS Excel, then try the methods discussed above to resolve the issue. If the cause of the error is corruption in the Excel file, then use an advanced Excel Repair software, such as Stellar Repair for Excel to repair the corrupted Excel file.

About The Author

Monika Dadool

Monika Dadool is a Technical content writer at Stellar who writes about QuickBooks, Sage50, MySQL Database, Active Directory, e-mail recovery, Microsoft365, Pattern Recognition, and Machine learning. She loves researching, exploring new technology, and Developing engaging technical blogs that help organizations or Database Administrators fix multiple issues. When she isn’t creating content, she is busy on social media platforms, watching web series, reading books, and searching for food recipes.

Home > VBA > VBA Overflow Error (Error 6)

In VBA, Overflow (Error 6) is a run-time error that occurs when you specify a number to the variable that is out of the range of numbers which that data type can take. In simple words, this error occurs when you go out of the range for a variable’s type.

Let’s say you are using the Integer data type that can take values ranging from -32,768 to 32,767 so when you specify a value that is out of this range you get the Overflow run time error.

In the above example, you can see that we have used the integer data type for the iNum variable but while specifying the value we have used “10000000” which is way more than the range, and when you run the code Overflow run-time error occurs.

Sub myMacro()
Dim iNum As Integer
iNum = 10000000
End Sub

How to Deal with Overflow (VBA Error 6)

The way to deal with this error is to have a complete understanding of the VBA Data Types that you need to use while declaring a variable. You need to deal with a range of values when you are using a data type to store a numeric value in the variable. So, you need to examine the range of the result that you want to store in the variable.

What is VBA

  • VBA ERROR Handling
  • VBA Automation Error (Error 440)
  • VBA Error 400
  • VBA Invalid Procedure Call Or Argument Error (Error 5)
  • VBA Object Doesn’t Support this Property or Method Error (Error 438)
  • VBA Object Required Error (Error 424)
  • VBA Out of Memory Error (Error 7)
  • VBA Runtime Error (Error 1004)
  • VBA Subscript Out of Range Runtime Error (Error 9)
  • VBA Type Mismatch Error (Error 13)

 

Lera_Lera

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

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

Подскажите, пожалуйста, почему вылезает ошибка Overflow (Error 6) в коде?
Ошибка ссылается на строку, которая красным выделена.
Значение переменных Stavka и Srok берутся из ячеек на листе. Они в свою очередь меняются в цикле.
Если код в таком виде, то вылезает ошибка Overflow, но если переменную Stavka заменить на значение (например 0.065), то все работает корректно.

             a = Stavka / 12
             b = (1 + a) ^ Srok
            c = 1 / b
             d = K * a
           e = 1 — c
          EP = d / e

Изменено: Lera_Lera23.07.2014 17:19:54

 

ZVI

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

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

Нужно объявить Dim EP As Double
и проверять е на ноль: If e = 0 Then MsgBox «e=0» Else EP = d / e

Изменено: ZVI23.07.2014 17:28:49

 

Lera_Lera

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

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

EP у меня так и объявлено, а е — никак не может быть равным нулю. Может, в чем-нибудь другом проблема?

 

если случайно Stavka или Srok окажутся равными 0 (например, пустая ячейка), то тогда e вполне может оказаться = 0

 

Lera_Lera, а пошагово пройтись и посмотреть значения d и e?  

 

Hugo

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

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

Это такая задачка на сообразительность?
Что там ещё и как объявлено? Что на листе?

 

Lera_Lera

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

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

Разобралась, у меня адрес для Stavka некорректный был!
Спасибо за совет «If e = 0 Then MsgBox «e=0″ Else EP = d / e» Благодаря ему и поняла, что не так!
Большое спасибо!

 

S.K.

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

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

#8

03.06.2019 14:55:30

Всем добрый день, подскажите пожалуйста как быть?
Есть файл в который добавлена кнопка, в кнопке прописана команда:

Код
Private Sub CommandButton1_Click()
[L6] = IIf([l4] = "", "", IIf([l5] = "", "", IIf([o15] = 0, "", [o15] / [n29] * [l4])))
End Sub

Но при ее вызове вылетает ошибка
Overflow (Error 6)
В чем может быть проблема?

Изначально использовалась формула:
=ЕСЛИ(L4=»»;»»;ЕСЛИ(L5=»»;»»;ЕСЛИ(O15=0;»»;O15/N29*L4)))

Догадываюсь, что ошибку может вызывать наличие 0 в ячейке O15, но не знаю как это исправить.
Если O15>0, то все работает нормально.

Что в этом случае надо сделать?

Изменено: S.K.03.06.2019 15:01:36

Ку-Ку мой мальчик!..

 

Sanja

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

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

Конструкции с IIf зачастую вызывают ошибки, если один из ее аргументов является вычисляемым и, в свою очередь, тоже может вернуть ошибку. В таком случае (в случае вычисляемого аргумента) лучше разнести условия по разным конструкциям If…Then…End If

Изменено: Sanja03.06.2019 15:12:14

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

 

bedvit

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

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

Виталий

Возможно выражение [n29] * [l4] у вас дает в итоге ноль. Деление на ноль запрещены.

«Бритва Оккама» или «Принцип Калашникова»?

 

sokol92

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

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

#11

03.06.2019 16:31:40

К сожалению (по крайней мере, моему), VBA не поддерживает

сокращенную логику

. Каждый из следующих операторов вызовет ошибку деления на ноль:

Код
  Debug.Print IIf(True, 0, 1 / 0)
  Debug.Print Choose(1, 1, 1 / 0)
  If True Or 1 / 0 Then Debug.Print 1

Рецепт выписан коллегой в #9.

Изменено: sokol9203.06.2019 16:36:40

Владимир

 

Sanja

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

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

#12

03.06.2019 16:40:41

Код
If Range("L4") = "" Or Range("L5") = "" Or Range("O15") = 0 Then
    Range("L6") = ""
ElseIf Range("N29") <> 0 Then
    Range("L6") = Range("O15") / Range("N29") * Range("L4")
End If

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

 

S.K.

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

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

#13

03.06.2019 17:26:00

Sanja, Огромное спасибо! Все работает как надо =)

Кому интересно вот тот самый файл

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

  • Психологический возраст.xlsm (25.59 КБ)

Ку-Ку мой мальчик!..

Помогите пожалуйста разобраться. Все время возникает ошибка Runtime error ‘6’ Overflow в VBA.
Ошибка возникает в этой строке «If WBook.Cells(q, 7) = ArrayPhoneAll(i) Then»
В столбце находятся телефонные номера или email, если поменять номер столбца, никакой ошибки не возникает.

Sub RegisterComplaintsPhone()

Dim n As Integer
Dim q As Long

n = 1


    
Set WBook = Workbooks("ДС_Реестр жалоб ГЛ и ЧАТ 09.07.2021222.xlsx").Worksheets("ДС_ГЛ, ЧАТ")

ReDim ArrayPhone(n) As Variant       
ReDim ArraySuccess(n) As Variant     
ReDim ArrayResult(n) As Variant      
ReDim ArrayPhone(n) As Variant       
ReDim ArrayFIO(n) As Variant         
ReDim ArrayDS(n) As Variant          
ReDim ArrayEmployee(n) As Variant    
ReDim ArrayEmployeeAll(n) As Variant 
ReDim ArrayDSAll(n) As Variant       
ReDim ArrayPhoneAll(n) As Variant    
ReDim ArrayResultAll(n) As Variant

n = 1
For w = 2 To 300
    If Worksheets("ДС").Cells(w, 2) <> "" Then
        ArrayPhoneAll(n) = Worksheets("ДС").Cells(w, 14).Value
        ArrayEmployeeAll(n) = Worksheets("ДС").Cells(w, 3).Value
        ArrayResultAll(n) = Worksheets("ДС").Cells(w, 2).Value
        Worksheets("ДС").Cells(w, 19) = ArrayPhoneAll(n)
        Worksheets("ДС").Cells(w, 20) = ArrayEmployeeAll(n)
        Worksheets("ДС").Cells(w, 21) = ArrayResultAll(n)
        n = n + 1
        'ReDim Preserve ArrayDSAll(n)
        ReDim Preserve ArrayPhoneAll(n)
        ReDim Preserve ArrayEmployeeAll(n)
        ReDim Preserve ArrayResultAll(n)
    End If
Next

n = 1 

MsgBox ArrayPhoneAll(1)
For i = 1 To UBound(ArrayPhoneAll) - 1
    For q = 2 To 20000
        If WBook.Cells(q, 7) = ArrayPhoneAll(i) Then
            WBook.Cells(q, 31) = ArrayPhoneAll(i)
        End If
    Next
Next
End Sub

Понравилась статья? Поделить с друзьями:
  • Vba ошибка 80004005
  • Vba ошибка 5174
  • Vba ошибка 4605
  • Vba вызов ошибки
  • Vba вывод ошибки