Run time error 5 invalid procedure call or argument vba

I need help with this macro. Every time I run it, I get the error below. I thought it was a simple macro that I could have anybody on my team use to make it take a less time than they were taking...

I need help with this macro. Every time I run it, I get the error below. I thought it was a simple macro that I could have anybody on my team use to make it take a less time than they were taking to manually create this PivotTable every time they ran the report. However, it’s not working. Please see error below and advise. I emboldened and italicized the error.

Error

Sub LEDOTTR()
'
' LEDOTTR Macro
'

'
    Range("A87").Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
    ***ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Sheet1!R87C1:R8214C25", Version:=xlPivotTableVersion14).CreatePivotTable _
        TableDestination:="LED OTTR!R1C1", TableName:="PivotTable6", _
        DefaultVersion:=xlPivotTableVersion14***
    Sheets("LED OTTR").Select
    Cells(1, 1).Select
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("LED")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("Hierarchy name")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable6").PivotFields("LED").CurrentPage = "(All)"
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("LED")
        .PivotItems("LED Marine").Visible = False
        .PivotItems("LL48 Linear LED").Visible = False
        .PivotItems("Other").Visible = False
    End With
    ActiveSheet.PivotTables("PivotTable6").PivotFields("LED"). _
        EnableMultiplePageItems = True
    ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
        "PivotTable6").PivotFields("   Late " & Chr(10) & "Indicator"), "Sum of    Late " & Chr(10) & "Indicator", _
        xlSum
    ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
        "PivotTable6").PivotFields("Early /Ontime" & Chr(10) & "   Indicator"), _
        "Sum of Early /Ontime" & Chr(10) & "   Indicator", xlSum
End Sub

pnuts's user avatar

pnuts

57.8k11 gold badges85 silver badges137 bronze badges

asked May 29, 2015 at 20:01

user3067028's user avatar

1

The answer to your problem is located here.

Your sheet name in TableDestination:="LED OTTR!R1C1" needs to be surrounded with single quotes in order for it to work TableDestination:="'LED OTTR'!R1C1"

You will also have problems with the duplicated name if you do not delete this PivotTable before rerunning the code.

answered May 29, 2015 at 22:27

Byron Wall's user avatar

Byron WallByron Wall

3,9252 gold badges13 silver badges29 bronze badges

2

In my case the trouble was related to the region settings in Windows. I downloaded a (protected) xlsm file from the internet and always got the «Run Time Error 5 — Invalid Procedure Call or Argument» error when opening it. The other answer hinted to me that it may have to do with the language settings. The scripts in the file were obviously programmed in German while my Windows was set to an English region.

In Windows 10 Settings > Time & Language > Region I changed Region as well as Regional format to German. After restarting Excel, the file worked.

answered Feb 2, 2020 at 11:38

n1000's user avatar

n1000n1000

4,86810 gold badges36 silver badges64 bronze badges

I’ve run into this, and the error was caused by calling the Worksheet.ExportAsFixedFormat method on a hidden worksheet.

I just added the if worksheet.Visible Then condition to my code to prevent getting the Invalid Procedure Call or Argument error.

answered Aug 18, 2020 at 20:55

David Namenyi's user avatar

While installing macro file to excel 2016 ribbon window getting below error when I debug the error. Below section was highlighed in yellow collor when clicked on debug

Set one = Application.CommandBars(«Worksheet Menu Bar»).Controls.Add(Type:= _
msoControlPopup, before:=onecount)

answered Apr 26, 2022 at 13:30

Manoj Pedekar's user avatar

2

Return to VBA Code Examples

This article will explain the VBA runtime error 5.

vba error 5

VBA runtime error 5 is a somewhat obscure and not particularly common error. It is described as an ‘Invalid procedure call or argument’. It can occur when you have a value that is out of the range of an argument.

Value out of Range of an Argument

Say you record a macro to create a Pivot table.  The macro creates a new sheet as the destination for the Pivot table. The sheet number will be hard-coded into the code that the macro records.

For example:

Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Combined!R5C1:R17C4", Version:=7).CreatePivotTable TableDestination:= _
"Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion:=7
Sheets("Sheet1").Select

The function to create the Pivot Table is made up of a number of arguments, one of which for the CreatePivotTable method is Table Destination. In the code snippet provided, the table destination is Sheet 1

vba-error 5 pivot destination

Now, for some reason you may wish to delete Sheet 1 and then re-run this macro.  This is when the error would occur.

The macro will run the line:

Sheets.Add

Excel will add another sheet to your workbook but as Sheet1 has already been used (even though it has been deleted), it will take the next number – so will add in Sheet2.

However, the next line of the macro refers to the destination of the Pivot table as being Sheet1 which does not exist. An Error 5 will then occur as the value in the argument is invalid.

When the error occurs, clicking on Debug in the Error message box will highlight the error.

vba error 5 debug.

Empty String Argument

The same situation could occur if you were using an object like the FileSystemObject in Excel.

Consider the following code:

Private Sub TestObjects()
 Dim strItem As String
 Dim objFSO As Object
 Dim objFolder As Object

 strItem = "C:Data"
 Set objFSO = CreateObject("Scripting.FileSystemObject")
 Set objFolder = objFSO.GetFolder(strItem)
 MsgBox objFolder.Name
End Sub

If we run this code, we get the following message box showing the name of the folder eg: Data.

vba error 5 msgbox

However, let’s amend the code as shown below:

Private Sub TestObjects()
 Dim strItem As String
 Dim objFSO As Object
 Dim objFolder As Object

 strItem = ""
 Set objFSO = CreateObject("Scripting.FileSystemObject")
 Set objFolder = objFSO.GetFolder(strItem)
 MsgBox objFolder.Name
End Sub

Now when we run the code, we will get an error.

vba error 5 fso error

This is due to the fact that we are sending an empty string to the GetFolder method (strItem = “”). This is invalid so the error occurs.

Note if we sent an incorrect folder location, we would get a differnt Run-time error!

Incorrect Platform of Excel

This error can also occur if you have written a macro in a Windows version of Excel, and then you try to run the macro on a Macintosh version. The error may occur as the VBA code can differ slightly between platforms.

Содержание

  1. «Run-time error 5» when you use Mid(), Left(), or Right() function
  2. Symptoms
  3. Cause
  4. Vba runtime error 5 invalid procedure call or argument
  5. Answered by:
  6. Question
  7. Answers
  8. Как исправить время выполнения Ошибка 5 Неправильный вызов процедуры или аргумент
  9. How To Fix RunTime Error 5
  10. Определение «Invalid procedure call or argument»
  11. More on VBA Errors
  12. EXAMPLE 2: VBA Run Time Error 1004: That Name is already taken. Try a different One
  13. How to fix the Runtime Code 5 Invalid procedure call or argument

«Run-time error 5» when you use Mid(), Left(), or Right() function

For a Microsoft Word 97 version of this article, see 181102.

For a Microsoft Word 98 version of this article, see 181103.

For a Microsoft Word 2000 version of this article, see 201979.

In Microsoft Visual Basic for Applications (VBA), when you use the Mid(), Right(), or Left() function, you may receive the following error message:

Run-time error ‘5’: «Invalid procedure call or argument»

Symptoms

This behavior occurs when the length argument for the statement is negative.

The Mid() function returns a portion of a text string starting at a given character position. The syntax for the command is as follows

where is the text string to search, is the character position from which to start, and is the number of characters to return. If no argument is specified, or if there are fewer than characters in the text, the function returns all the characters from the position to the end of the string.

Cause

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

290140 How to run the sample code for the Office XP programs from Knowledge Base articles

To resolve this issue, be sure to test the length of the string, as in the following example:

Источник

Vba runtime error 5 invalid procedure call or argument

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

My very first post so I am missing here something please forgive me!!

I have been running this Macro for Microsoft Excel. I have been using this Macro I havent design this.

Now whenever I run this macro this giving me an error with Invalid Procedure Call or Argument = Run time Error = 5

I have tried to debug the it point me to below line.

ActiveWorkbook.Worksheets(«MEGs & Targets»).PivotTables(«PivotTable6»). _

PivotCache.CreatePivotTable TableDestination:=»Sheet6!A3″, TableName:= _

«PivotTable8», DefaultVersion:=xlPivotTableVersion10 — This is the point it actually STOP working.

Any help greatly appreciated.

Answers

There are really many reasons causes the procedure crash.

First you should be aware of how a PivotTable been created in background. If I want to create the first PivotTable for a workbook, Excel What it does first is create a PivotCache based on the data I specified, the next step is creating a PivotTable based on the PivotCache Excel just created in background at the place I specified.

Thus next time you want to create an another PivotTable based on the same data, what Excel actually does is creating a new PivotTable based on the PivotCache instead of the original data.

So if your workbook doesn’t contain a pt named «PivotTable6», or if the workbook does contain a pt named «PivotTable6» but the database of pt isn’t the database you want for the new one, or if the workbook has already created pt named «PivotTable8», or if..your code would crash.

Actually, we can’t directly use the code recorded by macro under most situations, we would have do some modifications or optimizations.

I would help if you could tell us what are trying to do.

I look forward to hearing of you.

Calvin Gao[MSFT]
MSDN Community Support | Feedback to us

Источник

Как исправить время выполнения Ошибка 5 Неправильный вызов процедуры или аргумент

В этой статье представлена ошибка с номером Ошибка 5, известная как Неправильный вызов процедуры или аргумент, описанная как Некоторая часть звонка не может быть завершена.

Информация об ошибке

Имя ошибки: Неправильный вызов процедуры или аргумент
Номер ошибки: Ошибка 5
Описание: Некоторая часть звонка не может быть завершена.
Программное обеспечение: Windows
Разработчик: Microsoft

Этот инструмент исправления может устранить такие распространенные компьютерные ошибки, как BSODs, зависание системы и сбои. Он может заменить отсутствующие файлы операционной системы и библиотеки DLL, удалить вредоносное ПО и устранить вызванные им повреждения, а также оптимизировать ваш компьютер для максимальной производительности.

О программе Runtime Ошибка 5

Время выполнения Ошибка 5 происходит, когда Windows дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!

  • Аргумент — аргумент — это значение, переданное функции, процедуре или программе командной строки.
  • Вызов — Вызов действие по вызову подпрограммы кода, внешней программы или сценария в среде программирования.
  • Процедура — процедура — это подпрограмма, которая не возвращает значение
Симптомы Ошибка 5 — Неправильный вызов процедуры или аргумент

Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.

Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.

(Неправильный вызов процедуры или аргумент) Repair Tool»/>
(Только для примера)

Причины Неправильный вызов процедуры или аргумент — Ошибка 5

При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.

Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.

Методы исправления

Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.

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

Источник

How To Fix RunTime Error 5

Ошибка во время выполнения 5 может привести к сбоям в работе и зависанию компьютера, а также к потенциальному заражению вирусом. Узнайте, как быстро и легко исправить эти ошибки во время выполнения Windows Operating System!

Определение «Invalid procedure call or argument»

Эксперты обычно называют «Invalid procedure call or argument» «ошибкой времени выполнения». Программисты работают через различные уровни отладки, пытаясь убедиться, что Windows Operating System как можно ближе к безошибочным. К сожалению, инженеры являются людьми и часто могут делать ошибки во время тестирования, отсутствует ошибка 5.

После установки программного обеспечения может появиться сообщение об ошибке «Some part of the call can’t be completed.». В случае обнаруженной ошибки 5 клиенты могут сообщить о наличии проблемы Microsoft Corporation по электронной почте или сообщать об ошибках. Затем программисты могут исправить эти ошибки в коде и включить исправление, которое можно загрузить с их веб-сайта. Если есть уведомление об обновлении Windows Operating System, это может быть решением для устранения таких проблем, как ошибка 5 и обнаруженные дополнительные проблемы.

More on VBA Errors

Subscript Out of Range (Error 9) | Type Mismatch (Error 13) | Runtime (Error 1004) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400

If you are trying to prepare for an interview check out these VBA Interview Questions and Answers. And if you found this tutorial helpful, you can support us to create more tutorials like this.

EXAMPLE 2: VBA Run Time Error 1004: That Name is already taken. Try a different One

This error is shown when we are trying to give the same name to a worksheet which has already been given to another worksheet in the same workbook. Given that we already have a sheet named “Sheet1″, we create a new sheet, we click on it so that it becomes the active sheet, and we try to name it “Sheet1″ by running the below code. We get an error immediately once we reach the sheet name changing line.

Источник

How to fix the Runtime Code 5 Invalid procedure call or argument

This article features error number Code 5, commonly known as Invalid procedure call or argument described as Some part of the call can’t be completed.

Error Information

Error name: Invalid procedure call or argument
Error number: Code 5
Description: Some part of the call can’t be completed.
Software: Windows
Developer: Microsoft

This repair tool can fix common computer errors like BSODs, system freezes and crashes. It can replace missing operating system files and DLLs, remove malware and fix the damage caused by it, as well as optimize your PC for maximum performance.

About Runtime Code 5

Runtime Code 5 happens when Windows fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.

Definitions (Beta)

Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!

  • Argument — An argument is a value passed to a function, procedure, or command line program
  • Call — A Call is the action of invoking a subroutine of code, an external program or a script in a programming environment
  • Procedure — A procedure is a subroutine that does not return a value
Symptoms of Code 5 — Invalid procedure call or argument

Runtime errors happen without warning. The error message can come up the screen anytime Windows is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.

There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.

(Invalid procedure call or argument) Repair Tool»/>
(For illustrative purposes only)

Causes of Invalid procedure call or argument — Code 5

During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.

Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.

Repair Methods

Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.

If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.

Источник

  • Remove From My Forums
  • Question

  • (Suddenly) When I start up Word 2007 I get a dialogue box withthe following message (I can’t copy and paste either or I would put it here):

    Visual Basic

    Runtime error ‘5’:

    Invalid procedure call or argument

    Four buttons: CONTINUE (greyed out), END (just brings up the same dialogue box again), DEBUG (greyed out), HELP (hangs up)

    I’ve tried loading my CD and doing «REPAIR» — no change.  Tried running MS Office Diagnostics (it was recommended to me on screen saying that I was having frequent crashes) — no problems found.

    Am tempted to uninstall and reinstall MS Office.  Godd idea???  If yes, what do I rsik losing?

    Thanks for any and all help,

Answers

  • This kind of question should really be asked in a Word newsgroup. It’s not about the development using the VSTO technology; it’s about Word’s behavior. You’ll find a list of newsgroups in the «Please Read First» message pinned at the top of the VSTO forum.

    What you’re getting indicates there’s a VBA macro stored in a template that’s loading when Word starts, and the macro is not able to execute correctly. You can test this by holding down the Ctrl key when starting Word. This starts in «Safe Mode» (with the installation defaults). The problem should disappear.

    In order to get rid of the problem you have to track down which template contains the macro. You can use the «Add-ins» tab in the Word Options (Office button) to see what is listed under the topic «Document related Add-ins». Any file listed there could be the culprit; the macro could also be in your Normal.dotm template (but that’s unlikely since you mention the Debug button is greyed out.

    In the «Location» column you should see the full path to each template. Probably, this is the Word Startup folder. You need to

    • Note the names of the files

    • Quit Word

    •  go to the folder

    • move all the templates to a different location

    • Start Word — the problem has likely disappeared

    • Go back to the Add-ins tab in the Word Options and from the «Manage» list select «Templates. Click «Go»

    • this opens a dialog box. Under «Global templates and Add-ins» click the «Add» button and navigate to the folder where you put the templates you moved. Select any one of them, then click «OK».

    Repeat the last two steps until you locate the template that’s causing the problem. Contact the company or person who provided you with the template (which probably has some tools you want to use) and inform them of the problem. The other files can be moved back to the original folder.

 

Добрый день!    
Подскажите, пожалуйста… вот на этой строчке выдает ран тайм 5:  
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _  
       «Лист2!r1c1:r350c8», Version:=xlPivotTableVersion12). _  
       CreatePivotTable TableDestination:=»Лист1!r1c1″, TableName:= _  
       «Сводная таблица1», DefaultVersion:=xlPivotTableVersion12  
записал рекордером но при прогоне выдает ошибку

 

agregator

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

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

 

wilddaemon

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

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

{quote}{login=Lamer}{date=08.12.2011 11:25}{thema=Сводная таблица. Ошибка run-time error 5}{post}Добрый день!    
Подскажите, пожалуйста… вот на этой строчке выдает ран тайм 5:  
записал рекордером но при прогоне выдает ошибку{/post}{/quote}  
так может там уже есть сводная таблица, а вы на неё еще одну накладываете, вот и ошибку выдает. Если так, то удалите предыдущую сводную таблицу да и запустите записанное.  
Думаю, что так.

 

agregator => если выложу пример то меня уволят сразу:) запрет на отсылку файлов.  

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

  Просто то что только что было записано рекордером сразу же и не работает. При чем я уже с этим сталкивался но не помню как я от этого избавился…

 

wilddaemon

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

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

{quote}{login=Lamer}{date=08.12.2011 05:12}{thema=}{post}  
wilddaemon =>  В другом макросе смотрю, код идентичный и все работает.  

  {/post}{/quote}  
может попробовать словить ошибку и вызвать Err.Description? Может тогда что-то проясниться?

 

{/post}{/quote}  
может попробовать словить ошибку и вызвать Err.Description? Может тогда что-то проясниться?{/post}{/quote}  

  А с этого места поподробнее можно? Как сие осуществить?

 

wilddaemon

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

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

в начале вашего кода (например перед строкой, которая выдает ошибку) поставить    

  On Error GoTo Errorcatch  

  «ваш код»  

  Exit Sub  
Errorcatch:  
MsgBox Err.Description  
End Sub

 

{quote}{login=wilddaemon}{date=08.12.2011 05:45}{thema=Re: Re: Re: }{post}в начале вашего кода (например перед строкой, которая выдает ошибку) поставить    

  On Error GoTo Errorcatch  

  «ваш код»  

  Exit Sub  
Errorcatch:  
MsgBox Err.Description  
End Sub{/post}{/quote}  

    Пишет  invalid procedure call or argument.  
То есть тот самый ран-тайм 5

 
 

А вы прикрепите маленький пример без секретной информации. Таблицу заполните словами: яблоки, апельсины, мандарины, тыквы и выложите её тут

 

{quote}{login=}{date=08.12.2011 05:57}{thema=}{post}А вы прикрепите маленький пример без секретной информации. Таблицу заполните словами: яблоки, апельсины, мандарины, тыквы и выложите её тут{/post}{/quote}  

  Да у меня и в этой нет секретной информации. но сам факт передачи файла доставит мне кучу проблем:)

 

Юрий М

Модератор

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

Контакты см. в профиле

 

wilddaemon

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

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

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

 

{quote}{login=wilddaemon}{date=08.12.2011 06:07}{thema=Re: Re: }{post}а может проблема не вэтой строке? я вот банально скопировал в новую книгу эту часть кода и всё создаётся.  
Может быть немного приоткрыть завесу над остальным содержимым кода? Может быть там следует рыться?{/post}{/quote}  

  Подсвечивается эта строка. но проблема похоже и правда не тут. сейчас удалил раскидывание по полям внутри сводной и спокойно эта строка отработала. Значит проблема где то тут:  

  ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _  
       «turn_allEXCEL!R1C1:R324C7», Version:=xlPivotTableVersion12). _  
       CreatePivotTable TableDestination:=»Свод!R1C1″, TableName:= _  
       «СводнаяТаблица3», DefaultVersion:=xlPivotTableVersion12  
   Sheets(«Свод»).Select  
   Cells(1, 1).Select  
   With ActiveSheet.PivotTables(«СводнаяТаблица1»).PivotFields(«Наименование»)  
       .Orientation = xlRowField  
       .Position = 1  
   End With  
   With ActiveSheet.PivotTables(«СводнаяТаблица1»).PivotFields(«Номер»)  
       .Orientation = xlRowField  
       .Position = 2  
   End With  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица3»).PivotFields(«Исходящий (Д)»), «Сумма по полю Исходящий (Д)» _  
       , xlSum  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица3»).PivotFields(«Исходящий (К)»), «Сумма по полю Исходящий (К)» _  
       , xlSum  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица3»).PivotFields(«Итого»), «Сумма по полю Итого», xlSum

 

На самом деле путаницы с наименованиями таблиц нет, везде при обработке одинаково.    
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _  
       «turn_allEXCEL!R1C1:R324C7», Version:=xlPivotTableVersion12). _  
       CreatePivotTable TableDestination:=»Свод!R1C1″, TableName:= _  
       «СводнаяТаблица3», DefaultVersion:=xlPivotTableVersion12  
   Sheets(«Свод»).Select  
   Cells(1, 1).Select  
   With ActiveSheet.PivotTables(«СводнаяТаблица1»).PivotFields(«Наименование»)  
       .Orientation = xlRowField  
       .Position = 1  
   End With  
   With ActiveSheet.PivotTables(«СводнаяТаблица1»).PivotFields(«Номер»)  
       .Orientation = xlRowField  
       .Position = 2  
   End With  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица1»).PivotFields(«Исходящий (Д)»), «Сумма по полю Исходящий (Д)» _  
       , xlSum  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица1»).PivotFields(«Исходящий (К)»), «Сумма по полю Исходящий (К)» _  
       , xlSum  
   ActiveSheet.PivotTables(«СводнаяТаблица1»).AddDataField ActiveSheet.PivotTables _  
       («СводнаяТаблица1»).PivotFields(«Итого»), «Сумма по полю Итого», xlSum

 

wilddaemon

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

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

Я что-то не понял … когда создаете сводную — ее имя СводнаяТаблица3, а дальше по коду — СводнаяТаблица1  
.. я что-то пропустил? .. или здесь ошибка?

 

{quote}{login=wilddaemon}{date=08.12.2011 06:23}{thema=Re: }{post}Я что-то не понял … когда создаете сводную — ее имя СводнаяТаблица3, а дальше по коду — СводнаяТаблица1  
.. я что-то пропустил? .. или здесь ошибка?{/post}{/quote}  

  Неее, имена везде одинаковые, просто решил поменять циферки а в создании не поменял

 

wilddaemon

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

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

ну я даже не знаю…  
попробуй тогда перед строкой ошибки написать    

  on error resume next    

  .. а так действительно, без файла и не разобраться … у меня например ваш код отработал без ошибок. Может быть тогда дело в данных внутри исходной таблицы (форматы там или еще что.. .может там текст какой-то затисался) … Попробуйте в вашем файле удалить все данные на листе turn_allEXCEL кроме заголовков и посмотрите что будет..

 

Похоже самый простой вариант будет заключаться в том что я приду домой сделаю аналогичный файл и выложу его сюда. Хотя не удивлюсь если дома у меня все будет работать:)))

 

{quote}{login=wilddaemon}{date=08.12.2011 06:41}{thema=Re: Re: Re: }{post}ну я даже не знаю…  
попробуй тогда перед строкой ошибки написать    

  on error resume next    

  .. а так действительно, без файла и не разобраться … у меня например ваш код отработал без ошибок. Может быть тогда дело в данных внутри исходной таблицы (форматы там или еще что.. .может там текст какой-то затисался) … Попробуйте в вашем файле удалить все данные на листе turn_allEXCEL кроме заголовков и посмотрите что будет..{/post}{/quote}  

      У меня сейчас в данных присутствует текст и числа. Даже и не знаю в чем проблема может быть. ведь при рекордере все спокойно делается и не возникает никаких проблем. но если тут же прогоняю код в ВБА то появляется ошибка.

 

вот пример с Вашим кодом! все работает.  
если ошибка на первой строке кода, возможно это из-за того что столбцов исходных данных меньше 7. или сводная с таким именем уже существует!  
попробуйте!

 

а вот еще пример.    
может пригодится.  
без листа Свод!

 

)))    
и еще пример.  
удобнее!

 

{quote}{login=AKSENOV048}{date=08.12.2011 07:22}{thema=}{post})))    
и еще пример.  
удобнее!{/post}{/quote}  

    Спасибо! Все работает! Теперь только так и буду прописывать сводные таблички!

 

Lamer

Гость

#25

09.12.2011 11:57:40

AKSENOV048 и wilddaemon спасибо Вам огромное за помощь:)

Понравилась статья? Поделить с друзьями:
  • Run time error 5 invalid memory access
  • Run time error 481 invalid picture
  • Run time error 462 the remote server machine does not exist or is unavailable
  • Run time error 457 this key is already associated with an element of this collection
  • Run time error 450 wrong number of arguments or invalid property assignment vba