I am getting a Runtime error 6 ‘overflow’ message on the following code upon arriving at the line starting with ‘minimo’. It was working fine until recently. After providing some cosmetic-type updates to its underlying form this message has arrived and I can’t understand why.
'Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "select min(autonumerazione) from tblDashboard01", CurrentProject.Connection
Do While Not rs.EOF
minimo = rs.Fields(0)
rs.MoveNext
Loop
minimo = minimo - 1
st_Sql = "update tbldashboard01 set MasterLevel = autonumerazione - " & minimo & ""
Application.DoCmd.RunSQL (st_Sql)
Erik A
31.3k11 gold badges43 silver badges62 bronze badges
asked Jan 20, 2015 at 19:11
1
Try inserting the following line at the start of the program:
Dim minimo as Long
answered Jan 20, 2015 at 19:23
4
MS Access Run-Time Errors
Microsoft Access Visual Basic
Microsoft Access run-time errors listing. We will fill in a discussion of each of the runtime errors you typically encounter while developing an Access database. Some errors are simple to understand and fix, while others see very confusing and lack sufficient detail to provide any route for fixing them.
RunTime Error Table
ErrorError_DescriptionDiscussionRun-Time Error 3
Return without GoSub Run-Time Error 5
Invalid procedure call or argument Run-Time Error 6
Overflow Run-Time Error 7
Out of memory Run-Time Error 9
Subscript out of range Run-Time Error 10
This array is fixed or temporarily locked Run-Time Error 11
Division by zero Run-Time Error 13
Type mismatch Run-Time Error 14
Out of string space Run-Time Error 16
Expression too complex Run-Time Error 17
Can|t perform requested operation Run-Time Error 18
User interrupt occurred Run-Time Error 20
Resume without error Run-Time Error 28
Out of stack space Run-Time Error 35
Sub or Function not defined Run-Time Error 47
Too many DLL application clients Run-Time Error 48
Error in loading DLL Run-Time Error 49
Bad DLL calling convention Run-Time Error 51
Internal error Run-Time Error 52
Bad file name or number Run-Time Error 53
File not found Run-Time Error 54
Bad file mode Run-Time Error 55
File already open Run-Time Error 57
Device I/O error Run-Time Error 58
File already exists Run-Time Error 59
Bad record length Run-Time Error 61
Disk full Run-Time Error 62
Input past end of file Run-Time Error 63
Bad record number Run-Time Error 67
Too many files Run-Time Error 68
Device unavailable Run-Time Error 70
Permission denied Run-Time Error 71
Disk not ready Run-Time Error 74
Can|t rename with different drive Run-Time Error 75
Path/File access error Run-Time Error 76
Path not found Run-Time Error 91
Object variable or With block variable not set Run-Time Error 92
For loop not initialized Run-Time Error 93
Invalid pattern string Run-Time Error 94
Invalid use of Null Run-Time Error 96
Unable to sink events of object because the object Run-Time Error 97
Can not call friend function on object which is no Run-Time Error 98
A property or method call cannot include a referen Run-Time Error 321
Invalid file format Run-Time Error 322
Can|t create necessary temporary file Run-Time Error 325
Invalid format in resource file Run-Time Error 380
Invalid property value Run-Time Error 381
Invalid property array index Run-Time Error 382
Set not supported at runtime Run-Time Error 383
Set not supported (read-only property) Run-Time Error 385
Need property array index Run-Time Error 387
Set not permitted Run-Time Error 393
Get not supported at runtime Run-Time Error 394
Get not supported (write-only property) Run-Time Error 422
Property not found Run-Time Error 423
Property or method not found Run-Time Error 424
Object required Run-Time Error 429
ActiveX component can|t create object Run-Time Error 430
Class does not support Automation or does not supp Run-Time Error 432
File name or class name not found during Automatio Run-Time Error 438
Object doesn|t support this property or method Run-Time Error 440
Automation error Run-Time Error 442
Connection to type library or object library for r Run-Time Error 443
Automation object does not have a default value Run-Time Error 445
Object doesn|t support this action Run-Time Error 446
Object doesn|t support named arguments Run-Time Error 447
Object doesn|t support current locale setting Run-Time Error 448
Named argument not found Run-Time Error 449
Argument not optional Run-Time Error 450
Wrong number of arguments or invalid property assi Run-Time Error 451
Property let procedure not defined and property ge Run-Time Error 452
Invalid ordinal Run-Time Error 453
Specified DLL function not found Run-Time Error 454
Code resource not found Run-Time Error 455
Code resource lock error Run-Time Error 457
This key is already associated with an element of Run-Time Error 458
Variable uses an Automation type not supported in Run-Time Error 459
Object or class does not support the set of events Run-Time Error 460
Invalid clipboard format Run-Time Error 461
Method or data member not found Run-Time Error 462
The remote server machine does not exist or is una Run-Time Error 463
Class not registered on local machine Run-Time Error 481
Invalid picture Run-Time Error 482
Printer error Run-Time Error 735
Can|t save file to TEMP Run-Time Error 744
Search text not found Run-Time Error 746
Replacements too long
-
runtime error 6 overflow
This is the Append query that I am trying to run and I am getting an overflow error.
This is the data I am multiplying by which is a double field size.
Any help would be appreciated.Thanks,
NickLast edited by nick243; 07-24-2017 at 09:34 AM.
Reason: Wrong Picture
-
Is the destination for the results a Double Number as well?
-
Get back to basics. Change it to a select query, does it still happen? Remove the fields one by one to determine the exact field causing the issue. If it only happens on the append, again remove all other fields and test with just the one.
-
It is not appending the error rate to the table it is just getting rid of anything from be1j query where the error rate is less than the dept rate * 1.2 . Am I reading the query correctly?
-
Originally Posted by aytee111
Get back to basics. Change it to a select query, does it still happen? Remove the fields one by one to determine the exact field causing the issue. If it only happens on the append, again remove all other fields and test with just the one.
I went back and did what you said, It is the error rate field that is prohibiting this query from working and giving the overflow error.
-
Are there null values in this field? Add Nz(…). Otherwise run the b-e-j1 query by itself and see if there are any values that don’t look right. Also in that query, add a new field with the same calculation. Altho this may be a table, in which case create a query with that calculation — it is easier to troubleshoot very basic queries.
Note: do some research on naming conventions. Tables are named tbl… or …tbl, queries qry… or …qry. Also get rid of spaces in names, no special characters except underscore (_), no reserved words such as Date, etc. These things will come back and bite you further down the road.
-
The calculation of a value called ErrorRate will usually involve mathematical division somewhere. How are you calculating that errorRate? Might there be a division by zero, or division by a very small number somewhere? Is ErrorRate a calculated field in the table?
-
Originally Posted by aytee111
Are there null values in this field? Add Nz(…). Otherwise run the b-e-j1 query by itself and see if there are any values that don’t look right. Also in that query, add a new field with the same calculation. Altho this may be a table, in which case create a query with that calculation — it is easier to troubleshoot very basic queries.
Note: do some research on naming conventions. Tables are named tbl… or …tbl, queries qry… or …qry. Also get rid of spaces in names, no special characters except underscore (_), no reserved words such as Date, etc. These things will come back and bite you further down the road.
I noticed there was an error# in error rate because one of them is dividing 0 by 0 . I have not seen any null. It is a query. I will keep looking at it. I keep searching the related tables for information.
-
That is what is causing your problem, then. Remove that error in that field by using Nz or checking for nulls in numeric fields before dividing, or whatever the case is.
I am new to VB. I was trying to insert a record into access database with data reader. I was getting OVERFLOW error at runtime. I tried to google a lot but did not really solve the problem. My understanding is that overflow error occurs when we assign values
that to variables that exceeds the maximum size of the data type. I do not see any such problems in my code. Can anyone please help me to fix this? Very urgent.
Following is my code
Private Sub InsertRecord(ByVal CustomerID As Integer)
Dim RowArray() As String = Split(Me.lblRow.Text)
Dim intPrice As Integer
Dim decTotalPrice As Decimal
Dim mySQL As String
Dim Lastvalue As Integer = -1
For i As Integer = 0 To RowArray.Length — 1
If RowArray(i) <> «» Then
Lastvalue += 1
RowArray(Lastvalue) = RowArray(i)
End If
Next
ReDim Preserve RowArray(Lastvalue)
Dim myConn As New OleDb.OleDbConnection(Mystrg)
Dim myComm As New OleDb.OleDbCommand
For i = 0 To RowArray.Length — 1
mySQL = «Insert Into Cust_Date(CustomerID,LocID,DateID,RowID) Values (» _
& CustomerID & «,» _
& intLocID & «,» _
& CInt(LTrim(Replace(Mid(frmMain.cmbLoc.Text, InStrRev(frmMain.cmbLoc.Text, » «)), «/», «»))) & «,'» & Mid(RowArray(i), 1, 1) & «‘» & «)»
myComm.CommandText = mySQL
myComm.Connection = myConn
Try
myConn.Open()
myComm.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, «Error»)
End Try
myConn.Close()
Next
End sub
Note: I am using Access database
The table structure for Cust_Date is as follows:
CustLocID Auto Number Size
CustomerID Number
LocID Number
DateID Number
RowID Text 5
Thanks
ylsv
Ошибка переполнения Excel VBA
Ошибки — неотъемлемая часть любого языка программирования, но понимание того, почему возникает эта ошибка, — это то, что выделяет вас из толпы на собеседованиях. Ошибки не странные Кодирование VBAКод VBA относится к набору инструкций, написанных пользователем на языке программирования приложений Visual Basic в редакторе Visual Basic (VBE) для выполнения определенной задачи.читать далее. Ошибки не являются преднамеренными, поэтому найти причину ошибки становится сложной задачей. В VBA у нас есть некоторые предопределенные ошибки, и знание о них позволяет очень быстро исправить ошибку. В этой статье мы расскажем вам об ошибке RUN TIME ERROR 6: Overflow. Следуйте полной статье, чтобы узнать об ошибке, причинах ошибки переполнения VBA и о том, как их исправить.
Что такое ошибка времени выполнения 6: ошибка переполнения в VBA?
Когда мы объявляем переменную, мы присваиваем им тип данных. Мы должны быть полностью осведомлены о плюсах и минусах каждого типа данных — здесь на сцену выходит ошибка времени выполнения 6: переполнение. Когда мы перегружаем тип данных значением, превышающим емкость типа данных, мы получим эту ошибку.
Вы можете использовать это изображение на своем веб-сайте, в шаблонах и т. д. Пожалуйста, предоставьте нам ссылку на авторствоСсылка на статью должна быть гиперссылкой
Например:
Источник: Ошибка переполнения VBA (wallstreetmojo.com)
Например: если вы объявите переменную как Байт.
Тусклый Число Как байт
Тип данных byte может содержать значения от 0 до 255. Теперь я назначу значение 240.
Число = 240
Это должно работать нормально, потому что назначенное нами значение меньше предела значения байта 255. В тот момент, когда мы присваиваем значение, превышающее 255, это приводит к ошибке Ошибка времени выполнения 6: переполнение.
Это общий обзор ошибки времени выполнения 6: переполнение. Мы подробно рассмотрим некоторые примеры.
Примеры ошибки времени выполнения 6: переполнение в VBA
Давайте посмотрим на несколько примеров ошибки переполнения VBA в Excel.
Пример 1: Ошибка переполнения с байтовым типом данных
Как я уже говорил, важно знать плюсы и минусы Тип данных VBAТип данных — это основной признак любой переменной. Он представляет, какой тип и диапазон значений мы можем хранить в переменной. Типы данных встроены в VBA, и пользователям или разработчикам необходимо знать, какое значение может храниться в каком типе данных.читать далее мы собираемся использовать. Например, посмотрите на приведенный ниже код.
Код:
Sub OverFlowError_Example1() Dim Number As Byte Number = 256 MsgBox Number End Sub
Для переменной «Число» я присвоил значение 256. Когда я запущу этот код, мы получим следующую ошибку.
Это связано с тем, что тип данных Байт может содержать значения от 0 до 255. Поэтому это вызывает ошибку. Чтобы исправить ошибку, нам нужно либо изменить тип данных, либо уменьшить значение, которое мы присвоили переменной «Число».
Пример 2: ошибка переполнения VBA с целочисленным типом данных
Целое число VBAВ VBA целое число — это тип данных, который может быть присвоен любой переменной и использоваться для хранения целочисленных значений. В VBA скобка для максимального числа целочисленных переменных, которые можно сохранить, аналогична скобке в других языках. Используя оператор DIM, любую переменную можно определить как целочисленную переменную.читать далее — это тип данных, который может содержать значения от -32768 до 32767. Например, посмотрите на приведенный ниже код.
Код:
Sub OverFlowError_Example2() Dim MyValue As Integer MyValue = 25656 MsgBox MyValue End Sub
Когда я запущу этот код, мы получим значение переменной «MyValue» в окне сообщения, то есть 25656.
Теперь я переназначу номер переменной как «45654».
Код:
Sub OverFlowError_Example2() Dim MyValue As Integer MyValue = 45654 MsgBox MyValue End Sub
Теперь, если я попытаюсь запустить код, это вызовет ошибку, потому что объявленный нами тип данных может содержать максимум 32767 для положительных чисел, а для отрицательных чисел предел равен -32768.
Пример 3: Ошибка переполнения VBA с длинным типом данных
Длинный тип данных является наиболее часто используемым типом данных в Excel VBA. Это может содержать значения от –2 147 483 648 до 2 147 486 647. Все, что выше, вызовет ошибку.
Код:
Sub OverFlowError_Example3() Dim MyValue As Long MyValue = 5000 * 457 MsgBox MyValue End Sub
Это вызовет ошибку переполнения.
Чтобы решить эту проблему, нам нужно использовать функцию CLNG в VBAVBA CLng или «VBA Convert to Long» — это встроенная функция Excel, упрощающая преобразование числовых значений или данных, превышающих лимит длинных данных, в допустимый тип данных.читать далее. Ниже приведен пример того же самого.
Код:
Sub OverFlowError_Example3() Dim MyValue As Long MyValue = CLng (5000) * 457 MsgBox MyValue End Sub
Это должно работать нормально.
Это обзор ошибки времени выполнения 6: переполнение.. Чтобы решить эту ошибку, нам нужно полностью знать типы данных. Так что вернитесь к основам, сделайте основы правильно, тогда все встанет на свои места.
Вы можете скачать этот шаблон Excel для ошибки переполнения VBA здесь — Шаблон Excel с ошибкой переполнения VBA
УЗНАТЬ БОЛЬШЕ >>
Post Views: 989
Leeto 7 / 7 / 3 Регистрация: 23.12.2011 Сообщений: 372 Записей в блоге: 1 |
||||
1 |
||||
01.02.2012, 13:03. Показов 27908. Ответов 7 Метки нет (Все метки)
Если поменять переменные на константы (см. то что закоментено) то все, ок. Заранее спасибо.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
01.02.2012, 13:03 |
Ответы с готовыми решениями: Проблема при обработке данных через VBA MS Access (Run Time Error 2004: Недостаточно памяти) Проблема с формулами в VBA Excel: Run-time error 1004. Application defined or object-defined error Я столкнулся с такой проблемой: я пишу вот такой код Ошибка run time error 6 overflow, что не так? (без cost.Text = c6 вроде сначала робил, а потом удалял и всё равно ошибка Private Sub CommandButton1_Click() h = InputBox("Введите… проблема DLL: Run-time error ‘453’: 7 |
15131 / 6405 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
01.02.2012, 14:09 |
2 |
Посмотрите, чему равны переменные: View — Locals Window. Или просто наводите курсор на на переменные. Миниатюры
1 |
7 / 7 / 3 Регистрация: 23.12.2011 Сообщений: 372 Записей в блоге: 1 |
|
01.02.2012, 19:37 [ТС] |
3 |
Посмотрите, чему равны переменные: View — Locals Window. Или просто наводите курсор на на переменные. Нет у меня не ноль, не в этом проблема. В этом легко убедиться если в соответствующие клетки подставить значения. У меня была идея, что мож значение при умножении и других манипуляциях выходят за декларированный (типом данных) диапазон. Но версия эта отпала после того как я подставил значения в качестве констант (см. закомментирование строки). Если отбросить вторую часть формулы и оставить только логарифм, тоже не работает. А если убрать логарифм и отставить только произведение, то все работает. Мистика =( Есть какие нибудь догадки? Пожалуйста.
0 |
здесь больше нет… 3372 / 1670 / 184 Регистрация: 03.02.2010 Сообщений: 1,219 |
|
01.02.2012, 20:47 |
4 |
Решениевместо того, чтобы людям перебирать бесконечное количество вариантов с 5-ю переменными, дал бы конкретную xl-книгу с указанием, что ты делаешь и где у тебя ошибка.
А если убрать логарифм и отставить только произведение, то все работает вот такие догадки у меня…
3 |
Leeto 7 / 7 / 3 Регистрация: 23.12.2011 Сообщений: 372 Записей в блоге: 1 |
||||||
03.02.2012, 16:35 [ТС] |
5 |
|||||
вместо того, чтобы людям перебирать бесконечное количество вариантов с 5-ю переменными, дал бы конкретную xl-книгу с указанием, что ты делаешь и где у тебя ошибка. вот такие догадки у меня…
Заранее спасибо Вложения
0 |
аналитика здесь больше нет… 3372 / 1670 / 184 Регистрация: 03.02.2010 Сообщений: 1,219 |
||||
03.02.2012, 16:59 |
6 |
|||
Решение 1) у меня ошибок не возникло 3) замени начало на:
4) процедура с названием …Function заставляет задуматься о вменяемости кода 6) = 1) ошибок не возникло
3 |
Leeto 7 / 7 / 3 Регистрация: 23.12.2011 Сообщений: 372 Записей в блоге: 1 |
||||||
03.02.2012, 18:03 [ТС] |
7 |
|||||
1) у меня ошибок не возникло 3) замени начало на:
4) процедура с названием …Function заставляет задуматься о вменяемости кода 6) = 1) ошибок не возникло Спасибо за критику кода . Странно эта ошибка ликвидировалась когда я @#$@#$ всякую по удалял. Вот в этом файле ошибка точно есть. Вложения
1 |
15131 / 6405 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
03.02.2012, 22:05 |
8 |
Вызвал подпрограмму наугад — получил Overflow, опять же потому что все переменные =0. В Sub CulculationDeltaFunction() — неопределенное имя dbCNF_d1 Добавлено через 8 минут
4) процедура с названием …Function заставляет задуматься о вменяемости кода Вообще-то это обычный метод объявления процедуры без параметров, но которая не видна из окна Alt+F8.
1 |
Errors are part and parcel of any coding language but finding why that error is coming is what makes you stand apart from the crowd in interviews. Errors are not strange to VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. However, errors are not intentional, so finding the cause for the error is a hard task. In VBA, we have some predefined errors, and knowing about them makes you quickly fix the bug. This article will show you the RUN TIME ERROR 6: Overflow. Follow the full article to learn about the error, the reasons for the VBA “Overflow error,” and how to fix them.
Table of contents
- Excel VBA OverFlow Error
- What is Run Time Error 6: Overflow Error in VBA?
- Examples of Run Time Error 6: OverFlow in VBA
- Example 1: OverFlow Error with Byte Data Type
- Example 2: VBA OverFlow Error with Integer Data Type
- Example 3: VBA OverFlow Error with Long Data Type
- Recommended Articles
What is Run Time Error 6: Overflow Error in VBA?
When we declare the variable, we assign a data type to them. We should be completely aware of each data type’s pros and cons—this is where “Run Time Error 6: Overflow” comes into the picture. When we overload the data type with a value, which is more than the capacity of the data type, then we will get this error.
You are free to use this image on your website, templates, etc., Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA OverFlow Error (wallstreetmojo.com)
For example: If you declare the variable as Byte.
Dim Number As Byte
The Byte data type can hold values from 0 to 255. Now, we will assign the value to 240.
Number = 240
It should work fine because the value we have assigned is less than the limit of Byte’s value of 255. However, the moment we assign the value, which is more than 255, it leads to the error of Run Time Error 6: Overflow.
It is the general overview of the Run Time Error 6: Overflow. Next, we will see some of the examples in detail.
Examples of Run Time Error 6: OverFlow in VBA
Let us see some examples of VBA overflow errors in Excel.
Example 1: OverFlow Error with Byte Data Type
Knowing the pros and cons of the VBA data typeData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more we will use is important. For example, look at the below code.
Code:
Sub OverFlowError_Example1() Dim Number As Byte Number = 256 MsgBox Number End Sub
For the variable “Number,”we have assigned the value as 256. Therefore, we will get the below error when we run this code.
The data type Byte can hold values from 0 to 255. So it causes an error. To fix the error, we either change the data type or reduce the value assigned to the variable “Number.”
Example 2: VBA OverFlow Error with Integer Data Type
VBA integerIn VBA, an integer is a data type that may be assigned to any variable and used to hold integer values. In VBA, the bracket for the maximum number of integer variables that can be kept is similar to that in other languages. Using the DIM statement, any variable can be defined as an integer variable.read more is a data type that can hold values from -32768 to 32767. For example, look at the below code.
Code:
Sub OverFlowError_Example2() Dim MyValue As Integer MyValue = 25656 MsgBox MyValue End Sub
When we run this code, we will get the variable “MyValue” value in the message box, i.e., 25656.
Now, we will reassign the number to the variable as “45654.”
Code:
Sub OverFlowError_Example2() Dim MyValue As Integer MyValue = 45654 MsgBox MyValue End Sub
Now, if I try to run the code, it will cause an error because the data type we have declared can only hold the maximum of 32767 for positive numbers, and for negative numbers, the limit is -32768.
Example 3: VBA OverFlow Error with Long Data Type
The Long data type is the most often used in Excel VBA. This can hold values from –2,147,483,648 to 2,147,486,647. Anything above that will cause an error.
Code:
Sub OverFlowError_Example3() Dim MyValue As Long MyValue = 5000 * 457 MsgBox MyValue End Sub
It will cause an overflow error.
We need to use the function CLNG in VBAVBA CLng or «VBA Convert to Long» is an in-built Excel function that facilitates converting the numerical values or data exceeding the long data type limit into the acceptable data type.read more to fix this issue. Below is an example of the same.
Code:
Sub OverFlowError_Example3() Dim MyValue As Long MyValue = CLng (5000) * 457 MsgBox MyValue End Sub
It should work fine.
It is the overview of the Run Time Error 6: Overflow.We must be completely aware of the data types to solve this error. So go back to basics, do the basics right, then everything will fall in place.
You can download this VBA Overflow Error Excel Template here – VBA OverFlow Error Excel Template
Recommended Articles
This article has been a guide to VBA Overflow Error. Here, we learn how Runtime Overflow Error 6 occurs in Excel VBA and how to handle this error, along with practical examples and a downloadable template. Below are some useful Excel articles related to VBA: –
- VBA Pivot Table
- Clear Contents in VBA
- Excel VBA On Error Goto 0
- How to Delete Files using VBA Code?
Помогите пожалуйста разобраться. Все время возникает ошибка 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