Overflow vba excel ошибка

Excel VBA OverFlow Error

Introduction to VBA Overflow Error

We encounter many types if error while working with VBA. Errors are called runtime errors when they have encountered an error while executing the code. Also, every code has some certain code assigned to it in the programming of VBA. In excel one such error is the VBA Overflow error. The code for this error is run time error 6 which means overflow in the programming of VBA. We will learn about this error in this article.

Now we know what that overflow error is a type of error now let us understand what this error means. If we declare any variable as a certain data type and the value of the variable is exceeding the limit of the data type of the variable we get the error for overflow. For example, if we define a variable as integer and we know that integer can hold values up to 32767 for positive numbers and -32768 for negative numbers. So if we provide any input beyond that range we will encounter overflow error in VBA.

Overflow error in layman terms means we overload a data type with the values it can hold. Such cases will encounter us to this error. So to avoid this error we need to be aware of what data type we are using so that we can prevent it.

We will see through various examples that how in different types of data types we will possibly encounter this error.

How to Use VBA Overflow Error in Excel?

We will learn how to use a VBA Overflow Error Function with few examples in excel.

You can download this VBA OverFlow Error Excel Template here – VBA OverFlow Error Excel Template

Example #1 – Overflow Error

For the first example let us use Integer data type. Let us try to overflow the values so that variables cannot store it and see the error we encounter.

Follow the below steps to use VBA Overflow Error function in Excel:

Step 1: To basically start with VBA first thing we need to do is enable our developer’s tab and then click on it to open VB Editor from Visual Basic option as shown in the screenshot below,

VBA OverFlow Error

Step 2: Click on it and insert a module as follows, Once we click on the module. Double click on it and it will open another window for us where we will write our code.

Module Error

Step 3: We will see a blank window on the right-hand side of us, declare a subfunction and that is how we start a macro as follows,

Code:

Sub Sample()

End Sub

VBA OverFlow Error

Step 4: Declare a variable as an integer so that it can hold integer value for us,

Code:

Sub Sample()

Dim A As Integer

End Sub

OverFlow Error Example 1.1

Step 5: Now in Variable A store such value which will overflow the data type as follows,

Code:

Sub Sample()

Dim A As Integer
A = 4896 * 5000

End Sub

OverFlow Error Example 1.2

Step 6: Now display the value of A using msgbox function,

Code:

Sub Sample()

Dim A As Integer
A = 4896 * 5000
MsgBox A

End Sub

OverFlow Error Example 1.3

Step 7: Run the above code and see what result we get,

VBA Overflow Error 1

We received this error because 4896*5000 is over the positive number limit for the integer data type to hold and variable A is overflowed by this value so we encounter this error.

Example #2 – Overflow Error

Now in this example let us BYTE data type. We know that byte data type can hold values from 0 to 255 but any values other than that range will give us an error. Let us find out.

Step 1: We already have our module inserted, we can work on the same one or create a new one. But let us work on the same module we inserted. Double click on the module to enter the code window again,

OverFlow Errror module 2

Step 2: Declare another sub-function as follows,

Code:

Sub Sample1()

End Sub

VBA OverFLow Error 2.1

Step 3: Declare a variable as data type BYTE as follows,

Code:

Sub Sample1()

Dim A As Byte

End Sub

OverFlow Error Example 2.2

Step 4: Now in Variable A store value above than 255 as follows,

Code:

Sub Sample1()

Dim A As Byte
A = 266

End Sub

Error example 2.4

Step 5: Use a msgbox function to display the value of A,

Code:

Sub Sample1()

Dim A As Byte
A = 266
MsgBox A

End Sub

Error example 2.6

Step 6: Let us run the above code by pressing F5 and see the result,

OverFlow Error 2

Step 7: Now let us try and change the value of A to 244 and rerun the code to see the result,

Code:

Sub Sample1()

Dim A As Byte
A = 244
MsgBox A

End Sub

VBA Example 2.7

Step 8: When we run the code again we see the following result,

Overflow 3

When we first run the code variable A has values more than the range a BYTE data type can hold, but in the second instance, the variable A has data in its data type range so we didn’t encounter the overflow error.

Example #3 – Overflow Error

Now let us use LONG data type as an example as it is the most used data type among programmers.

Step 1: We will again work in the same module we inserted earlier. We just need to double click the module and we are in it.

OverFlow Errror mdule 3

Step 2: Declare a sub-function as shown in the screenshot.

Code:

Sub Sample2()

End Sub

VBA OverFLow Error 3.1

Step 3: Declare a variable as a LONG data type as follows.

Code:

Sub Sample2()

Dim A As Long

End Sub

Example Error 3.2

Step 4: Now similar to above examples let us overflow this variable by making it hold values above its range as follows.

Code:

Sub Sample2()

Dim A As Long
A = 2000 * 365

End Sub

Example Error 3.3

Step 5: Use a msgbox function to display the value of A as follows.

Code:

Sub Sample2()

Dim A As Long
A = 2000 * 365
MsgBox A

End Sub

Example Error 3.4

Step 6: Click on the above Run Button and see that we encounter overflow error.

VBA OverFlow 4

Step 7: Now there is a method to overcome this error in long data type by using CLNG function as follows.

Code:

Sub Sample2()

Dim A As Long
A = CLng(2000) * 365
MsgBox A

End Sub

Example Error 3.5

Step 8: Now if we again run the code we can see the following result.

VBA OverFlow 5

Now, what did the CLNG Function do? It converted the value to a long integer which the variable can hold.

How to Overcome Overflow Error in VBA

When we encounter overflow error in VBA that means any one of our variables, not more is having some values which it cannot hold. We need to identify the variable and rectify it. Also, we have CLNG function for long data types to help us. But knowing our data type actually helps.

Things to Remember

There are certain things which we need to remember about overflow error in VBA:

  • Overflow error is a run time error.
  • The error code for overflow error is 6.
  • To overcome overflow error we must know what data type can hold how much values.
  • CLNG function helps in overflow error for long data types.

Recommended Articles

This is a guide to VBA Overflow Error. Here we discuss how to use Excel VBA Overflow Error Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Copy Paste
  2. VBA RGB
  3. VBA Subscript out of Range
  4. VBA XML

Icon Ex Номер ошибки: Ошибка 6
Название ошибки: Excel Vba Error Code 6 Overflow
Описание ошибки: Ошибка 6: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Сводка «Excel Vba Error Code 6 Overflow

Люди часто предпочитают ссылаться на «Excel Vba Error Code 6 Overflow» как на «ошибку времени выполнения», также известную как программная ошибка. Когда дело доходит до программного обеспечения, как Microsoft Excel, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 6, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

Ошибка 6 может столкнуться с пользователями Microsoft Excel, если они регулярно используют программу, также рассматривается как «Excel Vba Error Code 6 Overflow». В случае обнаруженной ошибки 6 клиенты могут сообщить о наличии проблемы Microsoft Corporation по электронной почте или сообщать об ошибках. Затем Microsoft Corporation исправит ошибки и подготовит файл обновления для загрузки. Таким образом при выполнении обновления программного обеспечения Microsoft Excel, он будет содержать исправление для устранения проблем, таких как ошибка 6.

Сбой во время запуска Microsoft Excel или во время выполнения, как правило, когда вы столкнетесь с «Excel Vba Error Code 6 Overflow». Рассмотрим распространенные причины ошибок ошибки 6 во время выполнения:

Ошибка 6 Crash — ошибка 6 блокирует любой вход, и это может привести к сбою машины. Это возникает, когда Microsoft Excel не работает должным образом или не знает, какой вывод будет подходящим.

Утечка памяти «Excel Vba Error Code 6 Overflow» — ошибка 6 утечка памяти приводит к увеличению размера Microsoft Excel и используемой мощности, что приводит к низкой эффективности систем. Потенциальные триггеры могут быть «бесконечным циклом», или когда программа выполняет «цикл» или повторение снова и снова.

Ошибка 6 Logic Error — логическая ошибка возникает, когда компьютер генерирует неправильный вывод, даже если пользователь предоставляет правильный ввод. Это видно, когда исходный код Microsoft Corporation включает дефект в анализе входных данных.

Microsoft Corporation проблемы с Excel Vba Error Code 6 Overflow чаще всего связаны с повреждением или отсутствием файла Microsoft Excel. Как правило, решить проблему можно заменой файла Microsoft Corporation. В некоторых случаях реестр Windows пытается загрузить файл Excel Vba Error Code 6 Overflow, который больше не существует; в таких ситуациях рекомендуется запустить сканирование реестра, чтобы исправить любые недопустимые ссылки на пути к файлам.

Классические проблемы Excel Vba Error Code 6 Overflow

Типичные ошибки Excel Vba Error Code 6 Overflow, возникающие в Microsoft Excel для Windows:

  • «Ошибка в приложении: Excel Vba Error Code 6 Overflow»
  • «Excel Vba Error Code 6 Overflow не является программой Win32. «
  • «Excel Vba Error Code 6 Overflow должен быть закрыт. «
  • «Excel Vba Error Code 6 Overflow не может быть найден. «
  • «Excel Vba Error Code 6 Overflow не найден.»
  • «Ошибка запуска программы: Excel Vba Error Code 6 Overflow.»
  • «Не удается запустить Excel Vba Error Code 6 Overflow. «
  • «Excel Vba Error Code 6 Overflow выйти. «
  • «Ошибка в пути к программному обеспечению: Excel Vba Error Code 6 Overflow. «

Проблемы Excel Vba Error Code 6 Overflow с участием Microsoft Excels возникают во время установки, при запуске или завершении работы программного обеспечения, связанного с Excel Vba Error Code 6 Overflow, или во время процесса установки Windows. При появлении ошибки Excel Vba Error Code 6 Overflow запишите вхождения для устранения неполадок Microsoft Excel и чтобы HelpMicrosoft Corporation найти причину.

Создатели Excel Vba Error Code 6 Overflow Трудности

Заражение вредоносными программами, недопустимые записи реестра Microsoft Excel или отсутствующие или поврежденные файлы Excel Vba Error Code 6 Overflow могут создать эти ошибки Excel Vba Error Code 6 Overflow.

В первую очередь, проблемы Excel Vba Error Code 6 Overflow создаются:

  • Поврежденные ключи реестра Windows, связанные с Excel Vba Error Code 6 Overflow / Microsoft Excel.
  • Вирус или вредоносное ПО, которые повредили файл Excel Vba Error Code 6 Overflow или связанные с Microsoft Excel программные файлы.
  • Другая программа (не связанная с Microsoft Excel) удалила Excel Vba Error Code 6 Overflow злонамеренно или по ошибке.
  • Другое приложение, конфликтующее с Excel Vba Error Code 6 Overflow или другими общими ссылками.
  • Microsoft Excel (Excel Vba Error Code 6 Overflow) поврежден во время загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

Excel VBA OverFlow Error

Introduction to VBA Overflow Error

We encounter many types if error while working with VBA. Errors are called runtime errors when they have encountered an error while executing the code. Also, every code has some certain code assigned to it in the programming of VBA. In excel one such error is the VBA Overflow error. The code for this error is run time error 6 which means overflow in the programming of VBA. We will learn about this error in this article.

Now we know what that overflow error is a type of error now let us understand what this error means. If we declare any variable as a certain data type and the value of the variable is exceeding the limit of the data type of the variable we get the error for overflow. For example, if we define a variable as integer and we know that integer can hold values up to 32767 for positive numbers and -32768 for negative numbers. So if we provide any input beyond that range we will encounter overflow error in VBA.

Overflow error in layman terms means we overload a data type with the values it can hold. Such cases will encounter us to this error. So to avoid this error we need to be aware of what data type we are using so that we can prevent it.

We will see through various examples that how in different types of data types we will possibly encounter this error.

How to Use VBA Overflow Error in Excel?

We will learn how to use a VBA Overflow Error Function with few examples in excel.

You can download this VBA OverFlow Error Excel Template here – VBA OverFlow Error Excel Template

Example #1 – Overflow Error

For the first example let us use Integer data type. Let us try to overflow the values so that variables cannot store it and see the error we encounter.

Follow the below steps to use VBA Overflow Error function in Excel:

Step 1: To basically start with VBA first thing we need to do is enable our developer’s tab and then click on it to open VB Editor from Visual Basic option as shown in the screenshot below,

VBA OverFlow Error

Step 2: Click on it and insert a module as follows, Once we click on the module. Double click on it and it will open another window for us where we will write our code.

Module Error

Step 3: We will see a blank window on the right-hand side of us, declare a subfunction and that is how we start a macro as follows,

Code:

Sub Sample()

End Sub

VBA OverFlow Error

Step 4: Declare a variable as an integer so that it can hold integer value for us,

Code:

Sub Sample()

Dim A As Integer

End Sub

OverFlow Error Example 1.1

Step 5: Now in Variable A store such value which will overflow the data type as follows,

Code:

Sub Sample()

Dim A As Integer
A = 4896 * 5000

End Sub

OverFlow Error Example 1.2

Step 6: Now display the value of A using msgbox function,

Code:

Sub Sample()

Dim A As Integer
A = 4896 * 5000
MsgBox A

End Sub

OverFlow Error Example 1.3

Step 7: Run the above code and see what result we get,

VBA Overflow Error 1

We received this error because 4896*5000 is over the positive number limit for the integer data type to hold and variable A is overflowed by this value so we encounter this error.

Example #2 – Overflow Error

Now in this example let us BYTE data type. We know that byte data type can hold values from 0 to 255 but any values other than that range will give us an error. Let us find out.

Step 1: We already have our module inserted, we can work on the same one or create a new one. But let us work on the same module we inserted. Double click on the module to enter the code window again,

OverFlow Errror module 2

Step 2: Declare another sub-function as follows,

Code:

Sub Sample1()

End Sub

VBA OverFLow Error 2.1

Step 3: Declare a variable as data type BYTE as follows,

Code:

Sub Sample1()

Dim A As Byte

End Sub

OverFlow Error Example 2.2

Step 4: Now in Variable A store value above than 255 as follows,

Code:

Sub Sample1()

Dim A As Byte
A = 266

End Sub

Error example 2.4

Step 5: Use a msgbox function to display the value of A,

Code:

Sub Sample1()

Dim A As Byte
A = 266
MsgBox A

End Sub

Error example 2.6

Step 6: Let us run the above code by pressing F5 and see the result,

OverFlow Error 2

Step 7: Now let us try and change the value of A to 244 and rerun the code to see the result,

Code:

Sub Sample1()

Dim A As Byte
A = 244
MsgBox A

End Sub

VBA Example 2.7

Step 8: When we run the code again we see the following result,

Overflow 3

When we first run the code variable A has values more than the range a BYTE data type can hold, but in the second instance, the variable A has data in its data type range so we didn’t encounter the overflow error.

Example #3 – Overflow Error

Now let us use LONG data type as an example as it is the most used data type among programmers.

Step 1: We will again work in the same module we inserted earlier. We just need to double click the module and we are in it.

OverFlow Errror mdule 3

Step 2: Declare a sub-function as shown in the screenshot.

Code:

Sub Sample2()

End Sub

VBA OverFLow Error 3.1

Step 3: Declare a variable as a LONG data type as follows.

Code:

Sub Sample2()

Dim A As Long

End Sub

Example Error 3.2

Step 4: Now similar to above examples let us overflow this variable by making it hold values above its range as follows.

Code:

Sub Sample2()

Dim A As Long
A = 2000 * 365

End Sub

Example Error 3.3

Step 5: Use a msgbox function to display the value of A as follows.

Code:

Sub Sample2()

Dim A As Long
A = 2000 * 365
MsgBox A

End Sub

Example Error 3.4

Step 6: Click on the above Run Button and see that we encounter overflow error.

VBA OverFlow 4

Step 7: Now there is a method to overcome this error in long data type by using CLNG function as follows.

Code:

Sub Sample2()

Dim A As Long
A = CLng(2000) * 365
MsgBox A

End Sub

Example Error 3.5

Step 8: Now if we again run the code we can see the following result.

VBA OverFlow 5

Now, what did the CLNG Function do? It converted the value to a long integer which the variable can hold.

How to Overcome Overflow Error in VBA

When we encounter overflow error in VBA that means any one of our variables, not more is having some values which it cannot hold. We need to identify the variable and rectify it. Also, we have CLNG function for long data types to help us. But knowing our data type actually helps.

Things to Remember

There are certain things which we need to remember about overflow error in VBA:

  • Overflow error is a run time error.
  • The error code for overflow error is 6.
  • To overcome overflow error we must know what data type can hold how much values.
  • CLNG function helps in overflow error for long data types.

Recommended Articles

This is a guide to VBA Overflow Error. Here we discuss how to use Excel VBA Overflow Error Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Copy Paste
  2. VBA RGB
  3. VBA Subscript out of Range
  4. VBA XML

I have the following line in Excel VBA:

ActiveCell.Offset(r, 1).Value = IIf(rs2.Fields("SalesRelatedCallsQTD").Value = 0, "--", FormatPercent(rs2.Fields("SoldCallsQTD").Value / rs2.Fields("SalesRelatedCallsQTD").Value, 2))

When I run the macro in Excel I get a «Run-time error ‘6’: Overflow» error.

I know there is the possibility of getting a 0 value in the denominator hence the use of IIf to check for this. Is it possible that Excel is still trying to calculate the

FormatPercent(rs2.Fields("SoldCallsQTD").Value / rs2.Fields("SalesRelatedCallsQTD").Value, 2)

and throwing the error? If so how do I get around this or is there something else wrong with this code?

EDIT

When I add a watch here are the values I get:

rs2.Fields("SalesRelatedCallsQTD").Value : 0 : Variant/Long 
rs2.Fields("SoldCallsQTD").Value : 0 : Variant/Long
rs2.Fields("SoldCallsQTD").Value / rs2.Fields("SalesRelatedCallsQTD").Value : <Overflow> : Variant/Integer

Home > VBA > VBA Overflow Error (Error 6)

puneet-gogia-excel-champs-09-06-23

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.

vba-overflow-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)

 

Alen

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

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

Всем доброго дня!  

  Помогите, пожалуйста, с кодом, мне не понятно почему происходит ошибка… ((  

  Задача макроса: в цикле открывать файлы (их может быть до 200 шт) – выбирать диапазон заполненных ячеек, копировать и вставлять значения ячеек в файл «сводный» на один лист друг под другом.  

  Те готовые решения, что  я нашла на сайте к моей задаче  к сожалению не подходят, потому что во-первых  мои исходники защищены паролем, во вторых 2007 excel (для 2003 версии есть работающий макрос).  

  При работе макрос выдает ошибку: overflow  

  Примеры во вложении (сводный файл, и файлик, откуда копируются данные)  

  Очень-очень вас прошу мне помочь!!!

 

Hugo

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

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

Для подсчёта строк Integer не годится, замените на Long.  
Обычно Oferflow бывает по этой причине.  

  Dim Srow As Integer ‘кол-во строк в исходном  
Dim i As Integer ‘ переменная для счетчика

 

Alen

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

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

Спасибо большое!!! только теперь выдает другую ошибку (((    

  Application-defined or object-defined error  

  в чем может тут может быть дело? ругается на строчку:  

  rgI.Range(rgI.Cells(i, 17)).Copy

 

GIG_ant

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

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

возможно у вас не описана переменная rgI с помощью Dim.

 

Alen

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

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

описана… может я тут код покажу, чтобы нагляднее было?    

    Sub TMsvodka(strFileName As String)  

  Dim wbkI As Workbook ‘исходники  
Dim shtI As Worksheet    
Dim rgI As Range    
Dim strFile As String    
Dim Srow As Long    
Dim i As Long    
Dim Scol As Long    

  Dim wbkSv As Workbook  ‘сводный  
Dim shtSv As Worksheet    
Dim rgSv As Range    
Dim SvRow As Long    
Dim SvCol As Long    

  Set wbkSv = ThisWorkbook    
Set shtSv = wbkSv.Worksheets(«Сводка»)    
Set rgSv = shtSv.Range(«A8»).CurrentRegion    

        Set wbkI = Application.Workbooks.Open(strPath & «\» & strFileName)      
Set shtI = wbkI.Sheets(«data»)    
Set rgI = shtI.UsedRange    

  Srow = rgI.Rows.Count    
Scol = 17    

  SvRow = rgSv.Rows.Count    
SvCol = 17    

  For i = 1 To Srow    
   rgI.Range(rgI.Cells(i, 17)).Copy  
   rgSv.Cells(SvRow + 1, 17).PasteSpecial xlPasteValuesAndNumberFormats  
   Application.CutCopyMode = False  
Next i  

  wbkI.Close False      
shtSv.Range(«A8»).Select  

  End Sub

 

KuklP

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

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

E-mail и реквизиты в профиле.

Кто Вам такой бред написал? Сильно не вникал, но попробуйте так:  
Sub TMsvodka(strFileName As String)  

  Dim wbkI As Workbook ‘исходная книга  
Dim shtI As Worksheet ‘исходный лист в исходной книге  
Dim rgI As Range ‘диапазон в исходном для копирования  
Dim strFile As String ‘это открываемый файл  
Dim Srow As Long ‘кол-во строк в исходном  
Dim i As Long ‘ переменная для счетчика  
Dim Scol As Long ‘кол-во столбцов в исходном  

  Dim wbkSv As Workbook ‘ сводный  
Dim shtSv As Worksheet ‘сводный лист  
Dim rgSv As Range ‘диапазон для вставки данных в сводном файле  
Dim SvRow As Long ‘число строк в сводном для определения последней заполненной  
Dim SvCol As Long ‘число столбцов в сводном  

  Set wbkSv = ThisWorkbook ‘сводный файл  
Set shtSv = wbkSv.Worksheets(«Сводка») ‘сводный лист  
Set rgSv = shtSv.Range(«A8»).CurrentRegion ‘ диапазон ячеек для вставки  

        Set wbkI = Application.Workbooks.Open(strPath & «\» & strFileName)    ‘открыть исходный файл  
Set shtI = wbkI.Sheets(«data») ‘определить исходный лист  
Set rgI = shtI.UsedRange ‘ диапазон в исходном  

  Srow = rgI.Rows.Count ‘ кол-во строк в исходном  
Scol = 17 ‘колво столбцов в исходном — всегда 17  

  SvRow = rgSv.Rows.Count ‘ кол-во строк в исходном  
SvCol = 17 ‘колво столбцов в сводном — всегда 17  

  For i = 1 To Srow ‘цикл для копирования и вставки строк  
   rgI.Range(rgI.Cells(i, 1), rgI.Cells(i, 17)).Copy  
   rgSv.Cells(SvRow + i, 1).PasteSpecial xlPasteValuesAndNumberFormats  
Next i  
Application.CutCopyMode = False  

  wbkI.Close False    ‘закрыть книгу без сохранения  
shtSv.Range(«A8»).Select  

  End Sub

Я сам — дурнее всякого примера! …

 

KuklP

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

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

E-mail и реквизиты в профиле.

Еще одно. Насчет 200 файлов Вы сильно погорячились. У Вас в приложенном файле 60000 строк копируется(хотя почти все они пустые). А всего на листе в 2003 65536 строк.

Я сам — дурнее всякого примера! …

 

Alen

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

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

:) Этот бред написала я… просто я еще только учусь :)  

  Спасибо огромнейшее, теперь работает!!!!    

  НО…  

  Пожалуйста, скажите, как сделать, чтобы не копировал 60 000 строк, а только те, что заполнены?

 

Hugo

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

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

Будет копировать меньше, если удалить в примере все строки после данных, включая ту с единицей в X60000. И сохранить файл!  
Но вообще я UsedRange избегаю использовать из-за таких сюрпризов, лучше ориентироваться на точно до конца заполненный столбец, что обычно бывает.  
Я так чуть упростил, попробуйте:  

  Sub TMsvodka(strFileName As String)  

     Dim Srow As Long    ‘кол-во строк в исходном  
   Dim rgSv As Range    ‘диапазон для вставки данных в сводном файле  
   Dim SvRow As Long    ‘число строк в сводном для определения последней заполненной  

     Set rgSv = ThisWorkbook.Worksheets(«Сводка»).Range(«A8»).CurrentRegion  
   SvRow = rgSv.Rows.Count    ‘ кол-во строк в исходном  

     With Application.Workbooks.Open(strPath & «\» & strFileName)  
       With .Sheets(«data»).UsedRange     ‘открыть исходный файл  
           Srow = .Rows.Count    ‘ кол-во строк в исходном  
           .Range(.Cells(1, 1), .Cells(Srow, 17)).Copy  
           rgSv.Cells(SvRow + 1, 1).PasteSpecial xlPasteValuesAndNumberFormats  
           Application.CutCopyMode = False  
       End With  
       .Close False    ‘закрыть книгу без сохранения  
   End With  
   ThisWorkbook.Worksheets(«Сводка»).Range(«A8»).Select  

  End Sub

 

Alen

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

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

Ура! Вы супер! Работает! =)  

  Но только с одним файлом. Если файла два — он вставляет поверх прежних данных (((  

  и еще вопрос: можно ли сделать так, чтобы он начинал копировать не с первой строки а с 6-ой?  
где это нужно исправить?

 

Hugo

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

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

Вставляет поверх вероятно потому, что    
ThisWorkbook.Worksheets(«Сводка»).Range(«A8»).CurrentRegion  
не включает в себя докопированные строки, т.к. там вероятно есть пустые строки.  
Нужно вместо CurrentRegion определять диапазон иначе, как и вместо UsedRange.  
Чтоб копировал не с перовой — замените тут первую единицу на что нужно:  
.Range(.Cells(1, 1), .Cells(Srow, 17)).Copy

 

Alen

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

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

Всё, теперь вроде работает!!!    

  Спасибо вам огромнейшее Hugo и KukLP за помощь!!!!!!! =)

 

Hugo

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

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

Как это? В секунду прочитали, исправили, проверили, ответили? :)

 

Alen

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

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

#14

28.10.2011 16:37:47

:)) я просто сама поняла как исправить  

  УФ! Я счастлива!! Мучилась целую неделю!!!!    

  Еще раз спасибо!!! =)

Alen

Понравилась статья? Поделить с друзьями:
  • Overflow adc ошибка онк 160
  • Overcooked 2 ошибка сети
  • Over heat ошибка
  • Overclocking failed ошибка
  • Outlook ошибка 0х80070057