Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Invalid outside procedure |
vblr6.chm1040051 |
vblr6.chm1040051 |
office |
46c00b2b-c656-9ad4-bff9-d341a6a7ecd5 |
06/08/2017 |
medium |
The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:
-
An executable statement, Static or ReDim, appears at module level.
Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.
Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Содержание
- Недопустимое значение за пределами процедуры
- Поддержка и обратная связь
- Invalid outside procedure
- Support and feedback
- Name already in use
- VBA-Docs / Language / Reference / User-Interface-Help / invalid-outside-procedure.md
- Compile Error: Invalid Outside Procedure
- Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Re: Compile Error: Invalid Outside Procedure
- Excel compile error invalid outside procedure
- Answered by:
- Question
- Answers
Недопустимое значение за пределами процедуры
Оператор должен использоваться в процедуре Sub или Function, или в процедуре свойства (Property Get, Property Let, Property Set). Эта ошибка имеет следующие причину и решение:
На уровне модуля обнаруживается исполняемый оператор Static или ReDim.
На уровне модуля Static не нужен, поскольку все переменные уровня модуля являются статическими. Используйте оператор Dim вместо ReDim на уровне модуля. Чтобы создать на этом уровне динамический массив, объявите его с помощью оператора Dim, используя пустые скобки.
Примечание На уровне модуля можно использовать только комментарии и декларативные утверждения, такие как Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public и Type. Операторы Sub, Function и Property используются не в тексте своих процедур, а в объявлении процедуры.
Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Invalid outside procedure
The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:
An executable statement, Static or ReDim, appears at module level.
Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.
Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Name already in use
VBA-Docs / Language / Reference / User-Interface-Help / invalid-outside-procedure.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
Invalid outside procedure
The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:
An executable statement, Static or ReDim, appears at module level.
Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.
Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
Источник
Compile Error: Invalid Outside Procedure
LinkBack
Thread Tools
Rate This Thread
Display
Compile Error: Invalid Outside Procedure
Hello, I hope that someone can help with the following problem.
I have created an Excel file on my desktop (in Excel 2007) that contains some basic macro commands. This file is saved to my Dropbox cloud folder.
I also have the same Dropbox cloud folder installed on my laptop.
When I open the same Excel file on my laptop (running Excel 2010) I get a Microsoft Visual Basic screen (that relates to one of the Macros) pop up and the message, ‘Compile Error: Invalid Outside Procedure’.
I can close the Microsoft Visual Basic screen pop ups and carry on editing the file, but each time a make a change the same thing happens again, and I cannot run the macros.
Any help on resolving this irritating issue would be much appreciated.
Re: Compile Error: Invalid Outside Procedure
The code module starts with Private Sub. () and ends with End sub. Check if you have any lines of data outside these 2.
Press Alt+F11 and it will bring up the code.
Re: Compile Error: Invalid Outside Procedure
Thank you for replying. I will try that. I am not very technical with Excel or computing, so please bear with me if I get it wrong. Do I press Alt+F11 when I am seeing the Visual Basic pop-ups?
Re: Compile Error: Invalid Outside Procedure
Close the popup or click on OK button if present. Then while looking at your excel file, press Alt+F11.
Re: Compile Error: Invalid Outside Procedure
ALT+F11 does not bring up anything on my laptop (it just allows me to adjust the speaker volume). Anyway, the visual basic pop-up looks like it is the code, and while I can see ‘End Sub’ when I scroll to the bottom of the code page, I cannot see ‘Private Sub’ anywhere on the page.
The page starts as follows:
‘
‘ Pricecomma Macro
‘ Inserts commas in the price to pay
‘
‘ Keyboard shortcut: Ctrl+p
‘
After that, there is all the specific macro code, and right at the bottom of that is, ‘End Sub’.
Re: Compile Error: Invalid Outside Procedure
put Private Sub Test() You can replace Test with anything.
Re: Compile Error: Invalid Outside Procedure
That seems to have sorted it! Thank you very much.
Re: Compile Error: Invalid Outside Procedure
Based on your last post in this thread, its apparent that you are satisfied with the solution(s) you’ve received and have solved your question, but you haven’t marked your thread as «SOLVED». I will do it for you this time.
In future, to mark your thread as Solved, you can do the following —
Select Thread Tools-> Mark thread as Solved.
Incase your issue is not solved, you can undo it as follows —
Select Thread Tools-> Mark thread as Unsolved.
Also, since you are relatively new to the forum, i would like to inform you that you can thank those who have helped you by clicking the small star icon located in the lower left corner of the post which helped you. This adds to the reputation of the person who has taken the time to help you.
Источник
Excel compile error invalid outside procedure
Answered by:
Question
I am trying to convert a string to UTF-8 in VBA-Excel, my final aim is to do URL-encoding to UTF-8.
After a lot of searches I found this code that can help me to implement, it uses the Encoding Class:
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Imports System
Imports System.Text
Imports Microsoft.VisualBasic
But when I put the code example in the excel-VBA editor I get an error «Invalid outside procedure».
Please help, what sould I do?
p.s: if anyone has an example that can implement all the URL encoding to UTF-8 I will be grathfull to.
Answers
If you want to ask your question in the VBA forum you can find it here
Coding4fun Be a good forum member mark posts that contain the answers to your questions or those that are helpful
Please format the code in your posts with the button . Makes it easier to read . Or use the Forum Code Formatter by JohnWein http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/bf977a14-d9d4-4e84-9784-bf76b9e23261
Hello elAlladin,
Thanks for your post.
VBA stands for Visual Basic for Applications which is available in Excel, and other office applications.
About VB.net, one can create a stand-alone windows application, which is not possible with VBA.
Check the following link about their detailed difference. Hope it helpful.
http://allfaq.org/forums/t/178686.aspx
http://answers.google.com/answers/threadview/id/217809.html
This forum is for VB.NET questions only (e.g. Visual Basic 2003, Visual Basic 2005, Visual Basic 2008).
For VBA questions,you could post it on VBA forums as bdbodger suggested for better and quicker support.
Best regards,
Liliane
Please mark the replies as answers if they help and unmark them if they provide no help. Thanks
Источник
For the life of me I cannot figure out why the following code is throwing a compile error with the message «Invalid outside procedure». It is highlighting the error on the starred line below.
Option Explicit
Dim shtThisSheet As Worksheets
**Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")**
Sub Formatting()
With shtThisSheet
With Range("A1")
.Font.Bold = True
.Font.Size = 14
.HorizontalAlignment = xlLeft
End With
With Range("A3:A6")
.Font.Bold = True
.Font.Italic = True
.Font.ColorIndex = 5
.InsertIndent 1
End With
With Range("B2:D2")
.Font.Bold = True
.Font.Italic = True
.Font.ColorIndex = 5
.HorizontalAlignment = xlRight
End With
With Range("B3:D6")
.Font.ColorIndex = 3
.NumberFormat = "$#,##0"
End With
End With
End Sub
Michael Liu
50.3k13 gold badges115 silver badges146 bronze badges
asked Feb 10, 2016 at 15:31
2
Set
statements aren’t allowed outside procedures. Move the Set
statement into the Formatting
procedure:
Sub Formatting()
Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")
...
(I’d move the Dim
statement into the procedure as well. I prefer to avoid global variables when possible.)
answered Feb 10, 2016 at 15:33
Michael LiuMichael Liu
50.3k13 gold badges115 silver badges146 bronze badges
3
You can declare variables as global, but you cannot set them outside of a procedure such as a sub or function.
If you need this variable as a global, then it’s best to set it on.
Workbook_Open()
If you do not need it as a global, then move both the declaration and the set statement into your procedure
answered Feb 10, 2016 at 18:36
-
06-13-2013, 03:43 AM
#1
Registered User
Compile Error: Invalid Outside Procedure
Hello, I hope that someone can help with the following problem.
I have created an Excel file on my desktop (in Excel 2007) that contains some basic macro commands. This file is saved to my Dropbox cloud folder.
I also have the same Dropbox cloud folder installed on my laptop.
When I open the same Excel file on my laptop (running Excel 2010) I get a Microsoft Visual Basic screen (that relates to one of the Macros) pop up and the message, ‘Compile Error: Invalid Outside Procedure’.
I can close the Microsoft Visual Basic screen pop ups and carry on editing the file, but each time a make a change the same thing happens again, and I cannot run the macros.
Any help on resolving this irritating issue would be much appreciated.
Thank you.
-
06-13-2013, 04:33 AM
#2
Re: Compile Error: Invalid Outside Procedure
The code module starts with Private Sub….() and ends with End sub. Check if you have any lines of data outside these 2.
Press Alt+F11 and it will bring up the code.
If I have helped, Don’t forget to add to my reputation (click on the star below the post)
Don’t forget to mark threads as «Solved» (Thread Tools->Mark thread as Solved)
Use code tags when posting your VBA code: [code] Your code here [/code]
-
06-13-2013, 04:41 AM
#3
Registered User
Re: Compile Error: Invalid Outside Procedure
Thank you for replying. I will try that. I am not very technical with Excel or computing, so please bear with me if I get it wrong. Do I press Alt+F11 when I am seeing the Visual Basic pop-ups?
-
06-13-2013, 04:44 AM
#4
Re: Compile Error: Invalid Outside Procedure
Close the popup or click on OK button if present. Then while looking at your excel file, press Alt+F11.
-
06-13-2013, 04:54 AM
#5
Registered User
Re: Compile Error: Invalid Outside Procedure
ALT+F11 does not bring up anything on my laptop (it just allows me to adjust the speaker volume). Anyway, the visual basic pop-up looks like it is the code, and while I can see ‘End Sub’ when I scroll to the bottom of the code page, I cannot see ‘Private Sub’ anywhere on the page.
The page starts as follows:
‘
‘ Pricecomma Macro
‘ Inserts commas in the price to pay
‘
‘ Keyboard shortcut: Ctrl+p
‘After that, there is all the specific macro code, and right at the bottom of that is, ‘End Sub’.
-
06-13-2013, 04:58 AM
#6
Re: Compile Error: Invalid Outside Procedure
Ok, just before
put Private Sub Test() You can replace Test with anything.
-
06-13-2013, 06:40 AM
#7
Registered User
Re: Compile Error: Invalid Outside Procedure
That seems to have sorted it! Thank you very much.
-
06-13-2013, 07:02 AM
#8
Re: Compile Error: Invalid Outside Procedure
Based on your last post in this thread, its apparent that you are satisfied with the solution(s) you’ve received and have solved your question, but you haven’t marked your thread as «SOLVED». I will do it for you this time.
In future, to mark your thread as Solved, you can do the following —
Select Thread Tools-> Mark thread as Solved.Incase your issue is not solved, you can undo it as follows —
Select Thread Tools-> Mark thread as Unsolved.Also, since you are relatively new to the forum, i would like to inform you that you can thank those who have helped you by clicking the small star icon located in the lower left corner of the post which helped you. This adds to the reputation of the person who has taken the time to help you.
- Remove From My Forums
-
Question
-
Hello all,
I am trying to convert a string to UTF-8 in VBA-Excel, my final aim is to do URL-encoding to UTF-8.
After a lot of searches I found this code that can help me to implement, it uses the Encoding Class:
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspxIt starts with:
Imports System
Imports System.Text
Imports Microsoft.VisualBasicBut when I put the code example in the excel-VBA editor I get an error «Invalid outside procedure».
Please help, what sould I do?
p.s: if anyone has an example that can implement all the URL encoding to UTF-8 I will be grathfull to.
Answers
-
This is VB.NET code and the classes/methods you want to use cannot be used in VBA directly. What you can do is to look for a replacement which can be used in VBA directly or to create a VB.NET DLL, expose the desired functionality to COM and then
reference the .NET assembly (or more specifically, the TLB) from VBA. However, I’d recomment to take the first of the two ways I described.
Herfried K. Wagner [MVP]
-
Marked as answer by
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
-
If you want to ask your question in the VBA forum you can find it here
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/c147bae1-c9db-4ae8-9557-43713004cc94
Coding4fun Be a good forum member mark posts that contain the answers to your questions or those that are helpful
Please format the code in your posts with the button . Makes it easier to read . Or use the Forum Code Formatter by JohnWein http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/bf977a14-d9d4-4e84-9784-bf76b9e23261-
Marked as answer by
Liliane Teng
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
-
Hello elAlladin,
Thanks for your post.
VBA stands for Visual Basic for Applications which is available in Excel, and other office applications.
About VB.net, one can create a stand-alone windows application, which is not possible with VBA.
Check the following link about their detailed difference. Hope it helpful.
http://allfaq.org/forums/t/178686.aspx
http://answers.google.com/answers/threadview/id/217809.htmlThis forum is for VB.NET questions only (e.g. Visual Basic 2003, Visual Basic 2005, Visual Basic 2008).
For VBA questions,you could post it on VBA forums as bdbodger suggested for better and quicker support.Best regards,
Liliane
Please mark the replies as answers if they help and unmark them if they provide no help. Thanks
-
Marked as answer by
Liliane Teng
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
-
#1
Excel prompt out an error message that : «Compile Error: Invalid Outside Procedure».
The code it highlights is «PR_Form» in code:
Code:
'-------------------------------------
'declaration of some PR Form variables
'-------------------------------------
Public Pr As Worksheet 'PR Form worksheet shorhand
Pr = ThisWorkbook.Worksheets("PR_Form") 'set value to Pr
I put this code outside subs.
How can I solve this problem?
Thanks!
Pivot Table Drill Down
Double-click any number in a pivot table to create a new report showing all detail rows that make up that number
dk
MrExcel MVP
-
#2
Hi
You can’t put executable code outside of procedures. You can declare variables and external functions (e.g. Windows API) but everything else must reside in some sort of procedure e.g. function, sub, property get/let/set.
Also, you need to use the Set keyword when assigning an object to an object variable i.e.
This:
Set Pr = ThisWorkbook.Worksheets(«PR_Form») ‘set value to Pr
not this:
Pr = ThisWorkbook.Worksheets(«PR_Form») ‘set value to Pr
HTH
DK
-
#3
Hi there,
Try this:
Code:
Set Pr = ThisWorkbook.Worksheets("PR_Form") 'set value to Pr
HTH
Robert
-
#4
Thanks DK and Robert,
I tried both of your solutions. I think DK’s correct. Thank you so much!
Thanks a lot for DK’s explanation too
Yours sincerely,
lolo^-^
Hi
You can’t put executable code outside of procedures. You can declare variables and external functions (e.g. Windows API) but everything else must reside in some sort of procedure e.g. function, sub, property get/let/set.
Also, you need to use the Set keyword when assigning an object to an object variable i.e.
This:
Set Pr = ThisWorkbook.Worksheets(«PR_Form») ‘set value to Prnot this:
Pr = ThisWorkbook.Worksheets(«PR_Form») ‘set value to PrHTH
DK
Hi all, I want to change all of the titles + series on one page of a workbook to another page. I’ve been using this code for multiple workbooks but for whatever reason the code on the new file pops up as Compile Error: Invalid outside procedure. Does anyone know why this could be?
Thanks!
This is the code:
‘ suppose I want to change all references from cage 11 to cage 16
oldtext = «cage 2»
newtext = «Cage 3»
Sub ReplaceChartProperties()
Dim sh As Worksheet
Dim chs As ChartObject
Dim oldChartTitle As String
Dim newChartTitle As String
Dim mySrs As Series
Set sh = ActiveSheet
‘Debug.Print sh.Name
‘Debug.Print sh.ChartObjects.Count
‘Check if there is any chart on the sheet
If sh.ChartObjects.Count > 0 Then
‘Iterate through charts on the sheet and print chart parent name and chart name to the immediate window
For Each chs In sh.ChartObjects
oldChartTitle = chs.Chart.ChartTitle.Text
newChartTitle = Replace(oldChartTitle, oldtext, newtext)
newChartTitle = Replace(oldChartTitle, UCase(oldtext), UCase(newtext))
chs.Chart.ChartTitle.Text = newChartTitle
For Each mySrs In chs.Chart.SeriesCollection
mySrs.Formula = WorksheetFunction.Substitute(mySrs.Formula, _
oldtext, newtext)
Debug.Print mySrs.Formula
Next
Next chs
End If
MsgBox «Process is complete !!»
End Sub
Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Загадочное сообщение от VB»invalid outside procedure»
Здравствуйте Алексей. Вы никогда не встречались с ошибкой «invalid outside procedure»?, на перевод хватает даже моего английского, – но при чём здесь внешняя процедура, — происходит присвоение строковых значений элементам массива VB выделяет имено строковое значение, массив объявлен как строковый,любуюсь на это сообщение третий день,за это время 4 раза переустановил VB никаких мыслей нет, если можете помогите
С уважением Нырков Сергей
- alibek
- Большой Человек
- Сообщения: 14204
- Зарегистрирован: 19.04.2002 (Пт) 11:40
- Откуда: Russia
Re: Загадочное сообщение от VB»invalid outside procedure»
alibek » 18.07.2009 (Сб) 19:47
Перенес.
Первое предупреждение.
Lasciate ogni speranza, voi ch’entrate.
- iGrok
- Артефакт VBStreets
- Сообщения: 4272
- Зарегистрирован: 10.05.2007 (Чт) 16:11
- Откуда: Сетевое сознание
Re: Загадочное сообщение от VB»invalid outside procedure»
iGrok » 18.07.2009 (Сб) 21:24
Нырков Сергей писал(а):но при чём здесь внешняя процедура
Вашего английского таки не хватило. Outside относится не к «procedure» а к «invalid». Соответственно, кардинально меняется и перевод.
label:
cli
jmp label
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Re: Загадочное сообщение от VB»invalid outside procedure»
Нырков Сергей » 19.07.2009 (Вс) 13:02
Это ответ на ответ.Поставил русский VB и получил сообщение «плохая внешняя процедура» Так-что перевод не при чем.У меня происходит присвоение строковых значений (кирилица) элементам массива, VB выделяет имено строковое значение (между кавычками), массив объявлен как строковый,любуюсь на это сообщение третий день,за это время 4 раза переустановил VB никаких мыслей нет, если кто может помогитеЕщё способ получить это сообщение – использовать array и не важно какие данные помещать в массив результат будет тем-же выделение первого элемента в массиве
Пробовал вариант с collection то-же самое
Если вирус то уж больно экзотический
С уважением Нырков Сергей
- alibek
- Большой Человек
- Сообщения: 14204
- Зарегистрирован: 19.04.2002 (Пт) 11:40
- Откуда: Russia
Re: Загадочное сообщение от VB»invalid outside procedure»
alibek » 19.07.2009 (Вс) 13:48
Нырков Сергей писал(а):Это ответ на ответ.Поставил русский VB и получил сообщение «плохая внешняя процедура»
Не рекомендуется ходить на форум в нетрезвом виде. Перечитай еще раз текст сообщения и вникни в смысл фразы «недопустимо за пределами процедуры». Что значит «за пределами» понимаешь?
Lasciate ogni speranza, voi ch’entrate.
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Re: Загадочное сообщение от VB»invalid outside procedure»
Нырков Сергей » 19.07.2009 (Вс) 20:38
Большое- пребольшое СПАСИБО. Я-бы никогда не перевел invalid как недопустимо, у меня этот блок находится в секции general и руссифицировал мой экземпляр VB такой-же переводчик как я,т.е. в одном месте я допустил две ошибки 1)засунул присвоение в секцию general,2) особо не вдумывался при переводе. Ещё раз спасибо, и удачи всем нам
Вернуться в Visual Basic 1–6
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 13