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!!
asked Sep 18, 2012 at 3:05
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
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 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.
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.
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.
- Click Repair to recover as much data from the workbook as possible.
- After repair, you will see a message as shown in the below figure.
- 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 |
Подскажите, пожалуйста, почему вылезает ошибка Overflow (Error 6) в коде? a = Stavka / 12 Изменено: Lera_Lera — 23.07.2014 17:19:54 |
ZVI Пользователь Сообщений: 4338 |
Нужно объявить Dim EP As Double Изменено: ZVI — 23.07.2014 17:28:49 |
Lera_Lera Пользователь Сообщений: 32 |
EP у меня так и объявлено, а е — никак не может быть равным нулю. Может, в чем-нибудь другом проблема? |
если случайно Stavka или Srok окажутся равными 0 (например, пустая ячейка), то тогда e вполне может оказаться = 0 |
|
Lera_Lera, а пошагово пройтись и посмотреть значения d и e? |
|
Hugo Пользователь Сообщений: 23371 |
Это такая задачка на сообразительность? |
Lera_Lera Пользователь Сообщений: 32 |
Разобралась, у меня адрес для Stavka некорректный был! |
S.K. Пользователь Сообщений: 55 |
#8 03.06.2019 14:55:30 Всем добрый день, подскажите пожалуйста как быть?
Но при ее вызове вылетает ошибка Изначально использовалась формула: Догадываюсь, что ошибку может вызывать наличие 0 в ячейке O15, но не знаю как это исправить. Что в этом случае надо сделать? Изменено: S.K. — 03.06.2019 15:01:36 Ку-Ку мой мальчик!.. |
||
Sanja Пользователь Сообщений: 14849 |
Конструкции с IIf зачастую вызывают ошибки, если один из ее аргументов является вычисляемым и, в свою очередь, тоже может вернуть ошибку. В таком случае (в случае вычисляемого аргумента) лучше разнести условия по разным конструкциям If…Then…End If Изменено: Sanja — 03.06.2019 15:12:14 Согласие есть продукт при полном непротивлении сторон. |
bedvit Пользователь Сообщений: 2517 Виталий |
Возможно выражение [n29] * [l4] у вас дает в итоге ноль. Деление на ноль запрещены. «Бритва Оккама» или «Принцип Калашникова»? |
sokol92 Пользователь Сообщений: 4456 |
#11 03.06.2019 16:31:40 К сожалению (по крайней мере, моему), VBA не поддерживает сокращенную логику . Каждый из следующих операторов вызовет ошибку деления на ноль:
Рецепт выписан коллегой в #9. Изменено: sokol92 — 03.06.2019 16:36:40 Владимир |
||
Sanja Пользователь Сообщений: 14849 |
#12 03.06.2019 16:40:41
Согласие есть продукт при полном непротивлении сторон. |
||
S.K. Пользователь Сообщений: 55 |
#13 03.06.2019 17:26:00 Sanja, Огромное спасибо! Все работает как надо =) Кому интересно вот тот самый файл Прикрепленные файлы
Ку-Ку мой мальчик!.. |
Помогите пожалуйста разобраться. Все время возникает ошибка 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